diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/README.rst b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/README.rst new file mode 100644 index 000000000000..682bb48230d1 --- /dev/null +++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OsLoginServiceTransport` is the ABC for all transports. +- public child `OsLoginServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OsLoginServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOsLoginServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OsLoginServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py index 17425643447a..0dad331f6072 100644 --- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -437,12 +441,12 @@ def update_ssh_public_key( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_ssh_public_key: gapic_v1.method_async.wrap_method( + self.create_ssh_public_key: self._wrap_method( self.create_ssh_public_key, default_timeout=None, client_info=client_info, ), - self.delete_posix_account: gapic_v1.method_async.wrap_method( + self.delete_posix_account: self._wrap_method( self.delete_posix_account, default_retry=retries.AsyncRetry( initial=0.1, @@ -457,7 +461,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.delete_ssh_public_key: gapic_v1.method_async.wrap_method( + self.delete_ssh_public_key: self._wrap_method( self.delete_ssh_public_key, default_retry=retries.AsyncRetry( initial=0.1, @@ -472,7 +476,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.get_login_profile: gapic_v1.method_async.wrap_method( + self.get_login_profile: self._wrap_method( self.get_login_profile, default_retry=retries.AsyncRetry( initial=0.1, @@ -487,7 +491,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.get_ssh_public_key: gapic_v1.method_async.wrap_method( + self.get_ssh_public_key: self._wrap_method( self.get_ssh_public_key, default_retry=retries.AsyncRetry( initial=0.1, @@ -502,7 +506,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.import_ssh_public_key: gapic_v1.method_async.wrap_method( + self.import_ssh_public_key: self._wrap_method( self.import_ssh_public_key, default_retry=retries.AsyncRetry( initial=0.1, @@ -517,7 +521,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.update_ssh_public_key: gapic_v1.method_async.wrap_method( + self.update_ssh_public_key: self._wrap_method( self.update_ssh_public_key, default_retry=retries.AsyncRetry( initial=0.1, @@ -534,8 +538,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("OsLoginServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest.py index 393c70d6212d..ae41fb314fb3 100644 --- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest.py +++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 empty_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.oslogin_v1.common.types import common +from google.cloud.oslogin_v1.types import oslogin + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseOsLoginServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from google.cloud.oslogin_v1.common.types import common -from google.cloud.oslogin_v1.types import oslogin - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import OsLoginServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -267,8 +263,8 @@ class OsLoginServiceRestStub: _interceptor: OsLoginServiceRestInterceptor -class OsLoginServiceRestTransport(OsLoginServiceTransport): - """REST backend transport for OsLoginService. +class OsLoginServiceRestTransport(_BaseOsLoginServiceRestTransport): + """REST backend synchronous transport for OsLoginService. Cloud OS Login API @@ -281,7 +277,6 @@ class OsLoginServiceRestTransport(OsLoginServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -335,21 +330,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -360,19 +346,34 @@ def __init__( self._interceptor = interceptor or OsLoginServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateSshPublicKey(OsLoginServiceRestStub): + class _CreateSshPublicKey( + _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey, OsLoginServiceRestStub + ): def __hash__(self): - return hash("CreateSshPublicKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.CreateSshPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -401,47 +402,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=users/*}/sshPublicKeys", - "body": "ssh_public_key", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey._get_http_options() + ) request, metadata = self._interceptor.pre_create_ssh_public_key( request, metadata ) - pb_request = oslogin.CreateSshPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OsLoginServiceRestTransport._CreateSshPublicKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -457,19 +445,33 @@ def __call__( resp = self._interceptor.post_create_ssh_public_key(resp) return resp - class _DeletePosixAccount(OsLoginServiceRestStub): + class _DeletePosixAccount( + _BaseOsLoginServiceRestTransport._BaseDeletePosixAccount, OsLoginServiceRestStub + ): def __hash__(self): - return hash("DeletePosixAccount") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.DeletePosixAccount") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -492,40 +494,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=users/*/projects/*}", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseDeletePosixAccount._get_http_options() + ) request, metadata = self._interceptor.pre_delete_posix_account( request, metadata ) - pb_request = oslogin.DeletePosixAccountRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOsLoginServiceRestTransport._BaseDeletePosixAccount._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseDeletePosixAccount._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = OsLoginServiceRestTransport._DeletePosixAccount._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -533,19 +524,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteSshPublicKey(OsLoginServiceRestStub): + class _DeleteSshPublicKey( + _BaseOsLoginServiceRestTransport._BaseDeleteSshPublicKey, OsLoginServiceRestStub + ): def __hash__(self): - return hash("DeleteSshPublicKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.DeleteSshPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -568,40 +573,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=users/*/sshPublicKeys/*}", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseDeleteSshPublicKey._get_http_options() + ) request, metadata = self._interceptor.pre_delete_ssh_public_key( request, metadata ) - pb_request = oslogin.DeleteSshPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOsLoginServiceRestTransport._BaseDeleteSshPublicKey._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseDeleteSshPublicKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = OsLoginServiceRestTransport._DeleteSshPublicKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -609,19 +603,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetLoginProfile(OsLoginServiceRestStub): + class _GetLoginProfile( + _BaseOsLoginServiceRestTransport._BaseGetLoginProfile, OsLoginServiceRestStub + ): def __hash__(self): - return hash("GetLoginProfile") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.GetLoginProfile") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -651,40 +659,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=users/*}/loginProfile", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseGetLoginProfile._get_http_options() + ) request, metadata = self._interceptor.pre_get_login_profile( request, metadata ) - pb_request = oslogin.GetLoginProfileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOsLoginServiceRestTransport._BaseGetLoginProfile._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseGetLoginProfile._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = OsLoginServiceRestTransport._GetLoginProfile._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -700,19 +697,33 @@ def __call__( resp = self._interceptor.post_get_login_profile(resp) return resp - class _GetSshPublicKey(OsLoginServiceRestStub): + class _GetSshPublicKey( + _BaseOsLoginServiceRestTransport._BaseGetSshPublicKey, OsLoginServiceRestStub + ): def __hash__(self): - return hash("GetSshPublicKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.GetSshPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -741,40 +752,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=users/*/sshPublicKeys/*}", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseGetSshPublicKey._get_http_options() + ) request, metadata = self._interceptor.pre_get_ssh_public_key( request, metadata ) - pb_request = oslogin.GetSshPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOsLoginServiceRestTransport._BaseGetSshPublicKey._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseGetSshPublicKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = OsLoginServiceRestTransport._GetSshPublicKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -790,19 +790,34 @@ def __call__( resp = self._interceptor.post_get_ssh_public_key(resp) return resp - class _ImportSshPublicKey(OsLoginServiceRestStub): + class _ImportSshPublicKey( + _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey, OsLoginServiceRestStub + ): def __hash__(self): - return hash("ImportSshPublicKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.ImportSshPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -831,47 +846,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=users/*}:importSshPublicKey", - "body": "ssh_public_key", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey._get_http_options() + ) request, metadata = self._interceptor.pre_import_ssh_public_key( request, metadata ) - pb_request = oslogin.ImportSshPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OsLoginServiceRestTransport._ImportSshPublicKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -887,19 +889,34 @@ def __call__( resp = self._interceptor.post_import_ssh_public_key(resp) return resp - class _UpdateSshPublicKey(OsLoginServiceRestStub): + class _UpdateSshPublicKey( + _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey, OsLoginServiceRestStub + ): def __hash__(self): - return hash("UpdateSshPublicKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OsLoginServiceRestTransport.UpdateSshPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -928,47 +945,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{name=users/*/sshPublicKeys/*}", - "body": "ssh_public_key", - }, - ] + http_options = ( + _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey._get_http_options() + ) request, metadata = self._interceptor.pre_update_ssh_public_key( request, metadata ) - pb_request = oslogin.UpdateSshPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OsLoginServiceRestTransport._UpdateSshPublicKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest_base.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest_base.py new file mode 100644 index 000000000000..373d8e1645e1 --- /dev/null +++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest_base.py @@ -0,0 +1,452 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.oslogin_v1.common.types import common +from google.cloud.oslogin_v1.types import oslogin + +from .base import DEFAULT_CLIENT_INFO, OsLoginServiceTransport + + +class _BaseOsLoginServiceRestTransport(OsLoginServiceTransport): + """Base REST backend transport for OsLoginService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "oslogin.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'oslogin.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateSshPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=users/*}/sshPublicKeys", + "body": "ssh_public_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.CreateSshPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseCreateSshPublicKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePosixAccount: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=users/*/projects/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.DeletePosixAccountRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseDeletePosixAccount._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSshPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=users/*/sshPublicKeys/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.DeleteSshPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseDeleteSshPublicKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLoginProfile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=users/*}/loginProfile", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.GetLoginProfileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseGetLoginProfile._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSshPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=users/*/sshPublicKeys/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.GetSshPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseGetSshPublicKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportSshPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=users/*}:importSshPublicKey", + "body": "ssh_public_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.ImportSshPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseImportSshPublicKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSshPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=users/*/sshPublicKeys/*}", + "body": "ssh_public_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = oslogin.UpdateSshPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOsLoginServiceRestTransport._BaseUpdateSshPublicKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseOsLoginServiceRestTransport",) diff --git a/packages/google-cloud-os-login/setup.py b/packages/google-cloud-os-login/setup.py index c395b1ea84fc..ff238bd85d9f 100644 --- a/packages/google-cloud-os-login/setup.py +++ b/packages/google-cloud-os-login/setup.py @@ -46,6 +46,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -88,6 +89,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py index 6fe4e7cec0ff..3b71f423e3e0 100644 --- a/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py +++ b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py @@ -22,19 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -44,6 +36,23 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore + from google.cloud.oslogin_v1.common.types import common from google.cloud.oslogin_v1.services.os_login_service import ( OsLoginServiceAsyncClient, @@ -53,10 +62,24 @@ from google.cloud.oslogin_v1.types import oslogin +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1171,27 +1194,6 @@ def test_create_ssh_public_key(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_create_ssh_public_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ssh_public_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.CreateSshPublicKeyRequest() - - def test_create_ssh_public_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1262,34 +1264,6 @@ def test_create_ssh_public_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_ssh_public_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ssh_public_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", - ) - ) - response = await client.create_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.CreateSshPublicKeyRequest() - - @pytest.mark.asyncio async def test_create_ssh_public_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1298,7 +1272,7 @@ async def test_create_ssh_public_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1337,7 +1311,7 @@ async def test_create_ssh_public_key_async( transport: str = "grpc_asyncio", request_type=oslogin.CreateSshPublicKeyRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1413,7 +1387,7 @@ def test_create_ssh_public_key_field_headers(): @pytest.mark.asyncio async def test_create_ssh_public_key_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1490,7 +1464,7 @@ def test_create_ssh_public_key_flattened_error(): @pytest.mark.asyncio async def test_create_ssh_public_key_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1523,7 +1497,7 @@ async def test_create_ssh_public_key_flattened_async(): @pytest.mark.asyncio async def test_create_ssh_public_key_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1571,27 +1545,6 @@ def test_delete_posix_account(request_type, transport: str = "grpc"): assert response is None -def test_delete_posix_account_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_posix_account), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_posix_account() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.DeletePosixAccountRequest() - - def test_delete_posix_account_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1661,27 +1614,6 @@ def test_delete_posix_account_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_posix_account_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_posix_account), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_posix_account() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.DeletePosixAccountRequest() - - @pytest.mark.asyncio async def test_delete_posix_account_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1690,7 +1622,7 @@ async def test_delete_posix_account_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1729,7 +1661,7 @@ async def test_delete_posix_account_async( transport: str = "grpc_asyncio", request_type=oslogin.DeletePosixAccountRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1794,7 +1726,7 @@ def test_delete_posix_account_field_headers(): @pytest.mark.asyncio async def test_delete_posix_account_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1866,7 +1798,7 @@ def test_delete_posix_account_flattened_error(): @pytest.mark.asyncio async def test_delete_posix_account_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1895,7 +1827,7 @@ async def test_delete_posix_account_flattened_async(): @pytest.mark.asyncio async def test_delete_posix_account_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1942,27 +1874,6 @@ def test_delete_ssh_public_key(request_type, transport: str = "grpc"): assert response is None -def test_delete_ssh_public_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ssh_public_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.DeleteSshPublicKeyRequest() - - def test_delete_ssh_public_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2033,27 +1944,6 @@ def test_delete_ssh_public_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_ssh_public_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ssh_public_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.DeleteSshPublicKeyRequest() - - @pytest.mark.asyncio async def test_delete_ssh_public_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2062,7 +1952,7 @@ async def test_delete_ssh_public_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2101,7 +1991,7 @@ async def test_delete_ssh_public_key_async( transport: str = "grpc_asyncio", request_type=oslogin.DeleteSshPublicKeyRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2166,7 +2056,7 @@ def test_delete_ssh_public_key_field_headers(): @pytest.mark.asyncio async def test_delete_ssh_public_key_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2238,7 +2128,7 @@ def test_delete_ssh_public_key_flattened_error(): @pytest.mark.asyncio async def test_delete_ssh_public_key_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2267,7 +2157,7 @@ async def test_delete_ssh_public_key_flattened_async(): @pytest.mark.asyncio async def test_delete_ssh_public_key_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2317,27 +2207,6 @@ def test_get_login_profile(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_login_profile_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_login_profile), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_login_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.GetLoginProfileRequest() - - def test_get_login_profile_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2409,31 +2278,6 @@ def test_get_login_profile_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_login_profile_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_login_profile), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - oslogin.LoginProfile( - name="name_value", - ) - ) - response = await client.get_login_profile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.GetLoginProfileRequest() - - @pytest.mark.asyncio async def test_get_login_profile_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2442,7 +2286,7 @@ async def test_get_login_profile_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2481,7 +2325,7 @@ async def test_get_login_profile_async( transport: str = "grpc_asyncio", request_type=oslogin.GetLoginProfileRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2551,7 +2395,7 @@ def test_get_login_profile_field_headers(): @pytest.mark.asyncio async def test_get_login_profile_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2625,7 +2469,7 @@ def test_get_login_profile_flattened_error(): @pytest.mark.asyncio async def test_get_login_profile_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2656,7 +2500,7 @@ async def test_get_login_profile_flattened_async(): @pytest.mark.asyncio async def test_get_login_profile_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2712,27 +2556,6 @@ def test_get_ssh_public_key(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_ssh_public_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ssh_public_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.GetSshPublicKeyRequest() - - def test_get_ssh_public_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2802,34 +2625,6 @@ def test_get_ssh_public_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_ssh_public_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ssh_public_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", - ) - ) - response = await client.get_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.GetSshPublicKeyRequest() - - @pytest.mark.asyncio async def test_get_ssh_public_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2838,7 +2633,7 @@ async def test_get_ssh_public_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2877,7 +2672,7 @@ async def test_get_ssh_public_key_async( transport: str = "grpc_asyncio", request_type=oslogin.GetSshPublicKeyRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2953,7 +2748,7 @@ def test_get_ssh_public_key_field_headers(): @pytest.mark.asyncio async def test_get_ssh_public_key_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3025,7 +2820,7 @@ def test_get_ssh_public_key_flattened_error(): @pytest.mark.asyncio async def test_get_ssh_public_key_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3054,7 +2849,7 @@ async def test_get_ssh_public_key_flattened_async(): @pytest.mark.asyncio async def test_get_ssh_public_key_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3104,27 +2899,6 @@ def test_import_ssh_public_key(request_type, transport: str = "grpc"): assert response.details == "details_value" -def test_import_ssh_public_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_ssh_public_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.ImportSshPublicKeyRequest() - - def test_import_ssh_public_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3197,31 +2971,6 @@ def test_import_ssh_public_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_ssh_public_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_ssh_public_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - oslogin.ImportSshPublicKeyResponse( - details="details_value", - ) - ) - response = await client.import_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.ImportSshPublicKeyRequest() - - @pytest.mark.asyncio async def test_import_ssh_public_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3230,7 +2979,7 @@ async def test_import_ssh_public_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3269,7 +3018,7 @@ async def test_import_ssh_public_key_async( transport: str = "grpc_asyncio", request_type=oslogin.ImportSshPublicKeyRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3339,7 +3088,7 @@ def test_import_ssh_public_key_field_headers(): @pytest.mark.asyncio async def test_import_ssh_public_key_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3423,7 +3172,7 @@ def test_import_ssh_public_key_flattened_error(): @pytest.mark.asyncio async def test_import_ssh_public_key_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3462,7 +3211,7 @@ async def test_import_ssh_public_key_flattened_async(): @pytest.mark.asyncio async def test_import_ssh_public_key_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3520,27 +3269,6 @@ def test_update_ssh_public_key(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_update_ssh_public_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ssh_public_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.UpdateSshPublicKeyRequest() - - def test_update_ssh_public_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3611,34 +3339,6 @@ def test_update_ssh_public_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_ssh_public_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ssh_public_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", - ) - ) - response = await client.update_ssh_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == oslogin.UpdateSshPublicKeyRequest() - - @pytest.mark.asyncio async def test_update_ssh_public_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3647,7 +3347,7 @@ async def test_update_ssh_public_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3686,7 +3386,7 @@ async def test_update_ssh_public_key_async( transport: str = "grpc_asyncio", request_type=oslogin.UpdateSshPublicKeyRequest ): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3762,7 +3462,7 @@ def test_update_ssh_public_key_field_headers(): @pytest.mark.asyncio async def test_update_ssh_public_key_field_headers_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3844,7 +3544,7 @@ def test_update_ssh_public_key_flattened_error(): @pytest.mark.asyncio async def test_update_ssh_public_key_flattened_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3881,7 +3581,7 @@ async def test_update_ssh_public_key_flattened_async(): @pytest.mark.asyncio async def test_update_ssh_public_key_flattened_error_async(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3895,125 +3595,6 @@ async def test_update_ssh_public_key_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - oslogin.CreateSshPublicKeyRequest, - dict, - ], -) -def test_create_ssh_public_key_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "users/sample1"} - request_init["ssh_public_key"] = { - "key": "key_value", - "expiration_time_usec": 2144, - "fingerprint": "fingerprint_value", - "name": "name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = oslogin.CreateSshPublicKeyRequest.meta.fields["ssh_public_key"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ssh_public_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ssh_public_key"][field])): - del request_init["ssh_public_key"][field][i][subfield] - else: - del request_init["ssh_public_key"][field][subfield] - 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 = common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = common.SshPublicKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_ssh_public_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, common.SshPublicKey) - assert response.key == "key_value" - assert response.expiration_time_usec == 2144 - assert response.fingerprint == "fingerprint_value" - assert response.name == "name_value" - - def test_create_ssh_public_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4147,85 +3728,6 @@ def test_create_ssh_public_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_ssh_public_key_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_create_ssh_public_key" - ) as post, mock.patch.object( - transports.OsLoginServiceRestInterceptor, "pre_create_ssh_public_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = oslogin.CreateSshPublicKeyRequest.pb( - oslogin.CreateSshPublicKeyRequest() - ) - 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 = common.SshPublicKey.to_json(common.SshPublicKey()) - - request = oslogin.CreateSshPublicKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = common.SshPublicKey() - - client.create_ssh_public_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_ssh_public_key_rest_bad_request( - transport: str = "rest", request_type=oslogin.CreateSshPublicKeyRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "users/sample1"} - 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.create_ssh_public_key(request) - - def test_create_ssh_public_key_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4283,47 +3785,6 @@ def test_create_ssh_public_key_rest_flattened_error(transport: str = "rest"): ) -def test_create_ssh_public_key_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - oslogin.DeletePosixAccountRequest, - dict, - ], -) -def test_delete_posix_account_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/projects/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_posix_account(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_posix_account_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4444,79 +3905,6 @@ def test_delete_posix_account_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_posix_account_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "pre_delete_posix_account" - ) as pre: - pre.assert_not_called() - pb_message = oslogin.DeletePosixAccountRequest.pb( - oslogin.DeletePosixAccountRequest() - ) - 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() - - request = oslogin.DeletePosixAccountRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_posix_account( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_posix_account_rest_bad_request( - transport: str = "rest", request_type=oslogin.DeletePosixAccountRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/projects/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.delete_posix_account(request) - - def test_delete_posix_account_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4570,47 +3958,6 @@ def test_delete_posix_account_rest_flattened_error(transport: str = "rest"): ) -def test_delete_posix_account_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - oslogin.DeleteSshPublicKeyRequest, - dict, - ], -) -def test_delete_ssh_public_key_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_ssh_public_key(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_ssh_public_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4732,79 +4079,6 @@ def test_delete_ssh_public_key_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_ssh_public_key_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "pre_delete_ssh_public_key" - ) as pre: - pre.assert_not_called() - pb_message = oslogin.DeleteSshPublicKeyRequest.pb( - oslogin.DeleteSshPublicKeyRequest() - ) - 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() - - request = oslogin.DeleteSshPublicKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_ssh_public_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_ssh_public_key_rest_bad_request( - transport: str = "rest", request_type=oslogin.DeleteSshPublicKeyRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/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.delete_ssh_public_key(request) - - def test_delete_ssh_public_key_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4858,52 +4132,6 @@ def test_delete_ssh_public_key_rest_flattened_error(transport: str = "rest"): ) -def test_delete_ssh_public_key_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - oslogin.GetLoginProfileRequest, - dict, - ], -) -def test_get_login_profile_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1"} - 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 = oslogin.LoginProfile( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = oslogin.LoginProfile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_login_profile(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, oslogin.LoginProfile) - assert response.name == "name_value" - - def test_get_login_profile_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5040,83 +4268,6 @@ def test_get_login_profile_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_login_profile_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_get_login_profile" - ) as post, mock.patch.object( - transports.OsLoginServiceRestInterceptor, "pre_get_login_profile" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = oslogin.GetLoginProfileRequest.pb(oslogin.GetLoginProfileRequest()) - 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 = oslogin.LoginProfile.to_json(oslogin.LoginProfile()) - - request = oslogin.GetLoginProfileRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = oslogin.LoginProfile() - - client.get_login_profile( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_login_profile_rest_bad_request( - transport: str = "rest", request_type=oslogin.GetLoginProfileRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1"} - 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_login_profile(request) - - def test_get_login_profile_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5172,58 +4323,6 @@ def test_get_login_profile_rest_flattened_error(transport: str = "rest"): ) -def test_get_login_profile_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - oslogin.GetSshPublicKeyRequest, - dict, - ], -) -def test_get_ssh_public_key_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/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 = common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = common.SshPublicKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_ssh_public_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, common.SshPublicKey) - assert response.key == "key_value" - assert response.expiration_time_usec == 2144 - assert response.fingerprint == "fingerprint_value" - assert response.name == "name_value" - - def test_get_ssh_public_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5347,83 +4446,6 @@ def test_get_ssh_public_key_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_ssh_public_key_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_get_ssh_public_key" - ) as post, mock.patch.object( - transports.OsLoginServiceRestInterceptor, "pre_get_ssh_public_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = oslogin.GetSshPublicKeyRequest.pb(oslogin.GetSshPublicKeyRequest()) - 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 = common.SshPublicKey.to_json(common.SshPublicKey()) - - request = oslogin.GetSshPublicKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = common.SshPublicKey() - - client.get_ssh_public_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_ssh_public_key_rest_bad_request( - transport: str = "rest", request_type=oslogin.GetSshPublicKeyRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/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.get_ssh_public_key(request) - - def test_get_ssh_public_key_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5479,160 +4501,41 @@ def test_get_ssh_public_key_rest_flattened_error(transport: str = "rest"): ) -def test_get_ssh_public_key_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_import_ssh_public_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - oslogin.ImportSshPublicKeyRequest, - dict, - ], -) -def test_import_ssh_public_key_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert ( + client._transport.import_ssh_public_key + in client._transport._wrapped_methods + ) - # send a request that will satisfy transcoding - request_init = {"parent": "users/sample1"} - request_init["ssh_public_key"] = { - "key": "key_value", - "expiration_time_usec": 2144, - "fingerprint": "fingerprint_value", - "name": "name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_ssh_public_key + ] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = oslogin.ImportSshPublicKeyRequest.meta.fields["ssh_public_key"] + request = {} + client.import_ssh_public_key(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ssh_public_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ssh_public_key"][field])): - del request_init["ssh_public_key"][field][i][subfield] - else: - del request_init["ssh_public_key"][field][subfield] - 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 = oslogin.ImportSshPublicKeyResponse( - details="details_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = oslogin.ImportSshPublicKeyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_ssh_public_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, oslogin.ImportSshPublicKeyResponse) - assert response.details == "details_value" - - -def test_import_ssh_public_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.import_ssh_public_key - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.import_ssh_public_key - ] = mock_rpc - - request = {} - client.import_ssh_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.import_ssh_public_key(request) + client.import_ssh_public_key(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5738,87 +4641,6 @@ def test_import_ssh_public_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_ssh_public_key_rest_interceptors(null_interceptor): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OsLoginServiceRestInterceptor(), - ) - client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_import_ssh_public_key" - ) as post, mock.patch.object( - transports.OsLoginServiceRestInterceptor, "pre_import_ssh_public_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = oslogin.ImportSshPublicKeyRequest.pb( - oslogin.ImportSshPublicKeyRequest() - ) - 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 = oslogin.ImportSshPublicKeyResponse.to_json( - oslogin.ImportSshPublicKeyResponse() - ) - - request = oslogin.ImportSshPublicKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = oslogin.ImportSshPublicKeyResponse() - - client.import_ssh_public_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_ssh_public_key_rest_bad_request( - transport: str = "rest", request_type=oslogin.ImportSshPublicKeyRequest -): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "users/sample1"} - 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.import_ssh_public_key(request) - - def test_import_ssh_public_key_rest_flattened(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5879,55 +4701,1408 @@ def test_import_ssh_public_key_rest_flattened_error(transport: str = "rest"): ) -def test_import_ssh_public_key_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_update_ssh_public_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - oslogin.UpdateSshPublicKeyRequest, - dict, - ], -) -def test_update_ssh_public_key_rest(request_type): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/sample2"} - request_init["ssh_public_key"] = { - "key": "key_value", - "expiration_time_usec": 2144, - "fingerprint": "fingerprint_value", - "name": "name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Ensure method has been cached + assert ( + client._transport.update_ssh_public_key + in client._transport._wrapped_methods + ) - # Determine if the message type is proto-plus or protobuf - test_field = oslogin.UpdateSshPublicKeyRequest.meta.fields["ssh_public_key"] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_ssh_public_key + ] = mock_rpc - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + request = {} + client.update_ssh_public_key(request) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.update_ssh_public_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_ssh_public_key_rest_required_fields( + request_type=oslogin.UpdateSshPublicKeyRequest, +): + transport_class = transports.OsLoginServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_ssh_public_key._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() + ).update_ssh_public_key._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 + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = common.SshPublicKey() + # 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 + + # Convert return value to protobuf type + return_value = common.SshPublicKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_ssh_public_key(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_ssh_public_key_rest_unset_required_fields(): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_ssh_public_key._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "name", + "sshPublicKey", + ) + ) + ) + + +def test_update_ssh_public_key_rest_flattened(): + client = OsLoginServiceClient( + 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 = common.SshPublicKey() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "users/sample1/sshPublicKeys/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_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 + # Convert return value to protobuf type + return_value = common.SshPublicKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_ssh_public_key(**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/v1/{name=users/*/sshPublicKeys/*}" % client.transport._host, args[1] + ) + + +def test_update_ssh_public_key_rest_flattened_error(transport: str = "rest"): + client = OsLoginServiceClient( + 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_ssh_public_key( + oslogin.UpdateSshPublicKeyRequest(), + name="name_value", + ssh_public_key=common.SshPublicKey(key="key_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsLoginServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OsLoginServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsLoginServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OsLoginServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsLoginServiceGrpcTransport, + transports.OsLoginServiceGrpcAsyncIOTransport, + transports.OsLoginServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = OsLoginServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ssh_public_key_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ssh_public_key), "__call__" + ) as call: + call.return_value = common.SshPublicKey() + client.create_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.CreateSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_posix_account_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_posix_account), "__call__" + ) as call: + call.return_value = None + client.delete_posix_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeletePosixAccountRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_ssh_public_key_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_ssh_public_key), "__call__" + ) as call: + call.return_value = None + client.delete_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeleteSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_login_profile_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_login_profile), "__call__" + ) as call: + call.return_value = oslogin.LoginProfile() + client.get_login_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetLoginProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ssh_public_key_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ssh_public_key), "__call__" + ) as call: + call.return_value = common.SshPublicKey() + client.get_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_ssh_public_key_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_ssh_public_key), "__call__" + ) as call: + call.return_value = oslogin.ImportSshPublicKeyResponse() + client.import_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.ImportSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ssh_public_key_empty_call_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ssh_public_key), "__call__" + ) as call: + call.return_value = common.SshPublicKey() + client.update_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.UpdateSshPublicKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OsLoginServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_ssh_public_key_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + ) + await client.create_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.CreateSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_posix_account_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_posix_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_posix_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeletePosixAccountRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_ssh_public_key_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeleteSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_login_profile_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_login_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.LoginProfile( + name="name_value", + ) + ) + await client.get_login_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetLoginProfileRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_ssh_public_key_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + ) + await client.get_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_ssh_public_key_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + oslogin.ImportSshPublicKeyResponse( + details="details_value", + ) + ) + await client.import_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.ImportSshPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_ssh_public_key_empty_call_grpc_asyncio(): + client = OsLoginServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ssh_public_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + ) + await client.update_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.UpdateSshPublicKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OsLoginServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_ssh_public_key_rest_bad_request( + request_type=oslogin.CreateSshPublicKeyRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "users/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_ssh_public_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.CreateSshPublicKeyRequest, + dict, + ], +) +def test_create_ssh_public_key_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "users/sample1"} + request_init["ssh_public_key"] = { + "key": "key_value", + "expiration_time_usec": 2144, + "fingerprint": "fingerprint_value", + "name": "name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = oslogin.CreateSshPublicKeyRequest.meta.fields["ssh_public_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ssh_public_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ssh_public_key"][field])): + del request_init["ssh_public_key"][field][i][subfield] + else: + del request_init["ssh_public_key"][field][subfield] + 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 = common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = common.SshPublicKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_ssh_public_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + assert response.key == "key_value" + assert response.expiration_time_usec == 2144 + assert response.fingerprint == "fingerprint_value" + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ssh_public_key_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_create_ssh_public_key" + ) as post, mock.patch.object( + transports.OsLoginServiceRestInterceptor, "pre_create_ssh_public_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = oslogin.CreateSshPublicKeyRequest.pb( + oslogin.CreateSshPublicKeyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = common.SshPublicKey.to_json(common.SshPublicKey()) + req.return_value.content = return_value + + request = oslogin.CreateSshPublicKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.SshPublicKey() + + client.create_ssh_public_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_posix_account_rest_bad_request( + request_type=oslogin.DeletePosixAccountRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/projects/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_posix_account(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.DeletePosixAccountRequest, + dict, + ], +) +def test_delete_posix_account_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/projects/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_posix_account(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_posix_account_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "pre_delete_posix_account" + ) as pre: + pre.assert_not_called() + pb_message = oslogin.DeletePosixAccountRequest.pb( + oslogin.DeletePosixAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = oslogin.DeletePosixAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_posix_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_ssh_public_key_rest_bad_request( + request_type=oslogin.DeleteSshPublicKeyRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_ssh_public_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.DeleteSshPublicKeyRequest, + dict, + ], +) +def test_delete_ssh_public_key_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_ssh_public_key(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_ssh_public_key_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "pre_delete_ssh_public_key" + ) as pre: + pre.assert_not_called() + pb_message = oslogin.DeleteSshPublicKeyRequest.pb( + oslogin.DeleteSshPublicKeyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = oslogin.DeleteSshPublicKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_ssh_public_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_login_profile_rest_bad_request( + request_type=oslogin.GetLoginProfileRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_login_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.GetLoginProfileRequest, + dict, + ], +) +def test_get_login_profile_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1"} + 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 = oslogin.LoginProfile( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = oslogin.LoginProfile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_login_profile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, oslogin.LoginProfile) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_login_profile_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_get_login_profile" + ) as post, mock.patch.object( + transports.OsLoginServiceRestInterceptor, "pre_get_login_profile" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = oslogin.GetLoginProfileRequest.pb(oslogin.GetLoginProfileRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = oslogin.LoginProfile.to_json(oslogin.LoginProfile()) + req.return_value.content = return_value + + request = oslogin.GetLoginProfileRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = oslogin.LoginProfile() + + client.get_login_profile( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ssh_public_key_rest_bad_request( + request_type=oslogin.GetSshPublicKeyRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_ssh_public_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.GetSshPublicKeyRequest, + dict, + ], +) +def test_get_ssh_public_key_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/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 = common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = common.SshPublicKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_ssh_public_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + assert response.key == "key_value" + assert response.expiration_time_usec == 2144 + assert response.fingerprint == "fingerprint_value" + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ssh_public_key_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(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.OsLoginServiceRestInterceptor, "post_get_ssh_public_key" + ) as post, mock.patch.object( + transports.OsLoginServiceRestInterceptor, "pre_get_ssh_public_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = oslogin.GetSshPublicKeyRequest.pb(oslogin.GetSshPublicKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = common.SshPublicKey.to_json(common.SshPublicKey()) + req.return_value.content = return_value + + request = oslogin.GetSshPublicKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = common.SshPublicKey() + + client.get_ssh_public_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_ssh_public_key_rest_bad_request( + request_type=oslogin.ImportSshPublicKeyRequest, +): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "users/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_ssh_public_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + oslogin.ImportSshPublicKeyRequest, + dict, + ], +) +def test_import_ssh_public_key_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "users/sample1"} + request_init["ssh_public_key"] = { + "key": "key_value", + "expiration_time_usec": 2144, + "fingerprint": "fingerprint_value", + "name": "name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = oslogin.ImportSshPublicKeyRequest.meta.fields["ssh_public_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields runtime_nested_fields = [ (field.name, nested_field.name) @@ -5978,165 +6153,224 @@ def get_message_fields(field): # 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 = common.SshPublicKey( - key="key_value", - expiration_time_usec=2144, - fingerprint="fingerprint_value", - name="name_value", + return_value = oslogin.ImportSshPublicKeyResponse( + details="details_value", ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = common.SshPublicKey.pb(return_value) + return_value = oslogin.ImportSshPublicKeyResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_ssh_public_key(request) + response = client.import_ssh_public_key(request) # Establish that the response is the type that we expect. - assert isinstance(response, common.SshPublicKey) - assert response.key == "key_value" - assert response.expiration_time_usec == 2144 - assert response.fingerprint == "fingerprint_value" - assert response.name == "name_value" - + assert isinstance(response, oslogin.ImportSshPublicKeyResponse) + assert response.details == "details_value" -def test_update_ssh_public_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_ssh_public_key_rest_interceptors(null_interceptor): + transport = transports.OsLoginServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OsLoginServiceRestInterceptor(), + ) + client = OsLoginServiceClient(transport=transport) - # Ensure method has been cached - assert ( - client._transport.update_ssh_public_key - in client._transport._wrapped_methods + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OsLoginServiceRestInterceptor, "post_import_ssh_public_key" + ) as post, mock.patch.object( + transports.OsLoginServiceRestInterceptor, "pre_import_ssh_public_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = oslogin.ImportSshPublicKeyRequest.pb( + oslogin.ImportSshPublicKeyRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = oslogin.ImportSshPublicKeyResponse.to_json( + oslogin.ImportSshPublicKeyResponse() ) - client._transport._wrapped_methods[ - client._transport.update_ssh_public_key - ] = mock_rpc + req.return_value.content = return_value - request = {} - client.update_ssh_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = oslogin.ImportSshPublicKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = oslogin.ImportSshPublicKeyResponse() - client.update_ssh_public_key(request) + client.import_ssh_public_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_update_ssh_public_key_rest_required_fields( +def test_update_ssh_public_key_rest_bad_request( request_type=oslogin.UpdateSshPublicKeyRequest, ): - transport_class = transports.OsLoginServiceRestTransport - - 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, use_integers_for_enums=False) + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/sample2"} + request = request_type(**request_init) - # verify fields with default values are dropped + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_ssh_public_key(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_ssh_public_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.parametrize( + "request_type", + [ + oslogin.UpdateSshPublicKeyRequest, + dict, + ], +) +def test_update_ssh_public_key_rest_call_success(request_type): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - jsonified_request["name"] = "name_value" + # send a request that will satisfy transcoding + request_init = {"name": "users/sample1/sshPublicKeys/sample2"} + request_init["ssh_public_key"] = { + "key": "key_value", + "expiration_time_usec": 2144, + "fingerprint": "fingerprint_value", + "name": "name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_ssh_public_key._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) + # Determine if the message type is proto-plus or protobuf + test_field = oslogin.UpdateSshPublicKeyRequest.meta.fields["ssh_public_key"] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Designate an appropriate value for the returned response. - return_value = common.SshPublicKey() - # 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 + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields - response_value = Response() - response_value.status_code = 200 + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # Convert return value to protobuf type - return_value = common.SshPublicKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + subfields_not_in_runtime = [] - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ssh_public_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - response = client.update_ssh_public_key(request) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ssh_public_key"][field])): + del request_init["ssh_public_key"][field][i][subfield] + else: + del request_init["ssh_public_key"][field][subfield] + 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 = common.SshPublicKey( + key="key_value", + expiration_time_usec=2144, + fingerprint="fingerprint_value", + name="name_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_update_ssh_public_key_rest_unset_required_fields(): - transport = transports.OsLoginServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = common.SshPublicKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_ssh_public_key(request) - unset_fields = transport.update_ssh_public_key._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "name", - "sshPublicKey", - ) - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, common.SshPublicKey) + assert response.key == "key_value" + assert response.expiration_time_usec == 2144 + assert response.fingerprint == "fingerprint_value" + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6148,6 +6382,7 @@ def test_update_ssh_public_key_rest_interceptors(null_interceptor): else transports.OsLoginServiceRestInterceptor(), ) client = OsLoginServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -6169,10 +6404,10 @@ def test_update_ssh_public_key_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = common.SshPublicKey.to_json(common.SshPublicKey()) + return_value = common.SshPublicKey.to_json(common.SshPublicKey()) + req.return_value.content = return_value request = oslogin.UpdateSshPublicKeyRequest() metadata = [ @@ -6194,199 +6429,165 @@ def test_update_ssh_public_key_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_ssh_public_key_rest_bad_request( - transport: str = "rest", request_type=oslogin.UpdateSshPublicKeyRequest -): +def test_initialize_client_w_rest(): client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # send a request that will satisfy transcoding - request_init = {"name": "users/sample1/sshPublicKeys/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.update_ssh_public_key(request) + assert client is not None -def test_update_ssh_public_key_rest_flattened(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ssh_public_key_empty_call_rest(): client = OsLoginServiceClient( 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 = common.SshPublicKey() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ssh_public_key), "__call__" + ) as call: + client.create_ssh_public_key(request=None) - # get arguments that satisfy an http rule for this method - sample_request = {"name": "users/sample1/sshPublicKeys/sample2"} + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.CreateSshPublicKeyRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ssh_public_key=common.SshPublicKey(key="key_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = common.SshPublicKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.update_ssh_public_key(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_posix_account_empty_call_rest(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v1/{name=users/*/sshPublicKeys/*}" % client.transport._host, args[1] - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_posix_account), "__call__" + ) as call: + client.delete_posix_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeletePosixAccountRequest() + assert args[0] == request_msg -def test_update_ssh_public_key_rest_flattened_error(transport: str = "rest"): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_ssh_public_key_empty_call_rest(): client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_ssh_public_key( - oslogin.UpdateSshPublicKeyRequest(), - name="name_value", - ssh_public_key=common.SshPublicKey(key="key_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_ssh_public_key), "__call__" + ) as call: + client.delete_ssh_public_key(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.DeleteSshPublicKeyRequest() -def test_update_ssh_public_key_rest_error(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OsLoginServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_login_profile_empty_call_rest(): + client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.OsLoginServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OsLoginServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_login_profile), "__call__" + ) as call: + client.get_login_profile(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.OsLoginServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OsLoginServiceClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetLoginProfileRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OsLoginServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.OsLoginServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ssh_public_key_empty_call_rest(): + client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = OsLoginServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ssh_public_key), "__call__" + ) as call: + client.get_ssh_public_key(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsLoginServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OsLoginServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.GetSshPublicKeyRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OsLoginServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.OsLoginServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_ssh_public_key_empty_call_rest(): + client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_ssh_public_key), "__call__" + ) as call: + client.import_ssh_public_key(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.OsLoginServiceGrpcTransport, - transports.OsLoginServiceGrpcAsyncIOTransport, - transports.OsLoginServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.ImportSshPublicKeyRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = OsLoginServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ssh_public_key_empty_call_rest(): + client = OsLoginServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ssh_public_key), "__call__" + ) as call: + client.update_ssh_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = oslogin.UpdateSshPublicKeyRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -7028,36 +7229,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = OsLoginServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = OsLoginServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = OsLoginServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py index 668eac0d72ce..558c8aab67c5 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/gapic_version.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/gapic_version.py index 668eac0d72ce..558c8aab67c5 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/gapic_version.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/async_client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/async_client.py index 2d553f8706be..eb4209c23bd5 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/async_client.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/async_client.py @@ -1171,11 +1171,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1228,11 +1224,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1289,11 +1281,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1346,11 +1334,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1400,11 +1384,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1457,11 +1437,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/client.py index 20afd53a8928..e6116fefb2fe 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/client.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/client.py @@ -1639,11 +1639,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1696,11 +1692,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1757,11 +1749,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1814,11 +1802,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1868,11 +1852,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1925,11 +1905,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/README.rst b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/README.rst new file mode 100644 index 000000000000..5b77d01587ad --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ParallelstoreTransport` is the ABC for all transports. +- public child `ParallelstoreGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ParallelstoreGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseParallelstoreRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ParallelstoreRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/base.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/base.py index e62740dc2cd0..5d866cfea933 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/base.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/base.py @@ -165,6 +165,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/grpc_asyncio.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/grpc_asyncio.py index 721fc6fcc843..a11015f77620 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/grpc_asyncio.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -249,6 +250,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -478,46 +482,85 @@ def export_data( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=None, client_info=client_info, ), - self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=None, client_info=client_info, ), - self.create_instance: gapic_v1.method_async.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=None, client_info=client_info, ), - self.update_instance: gapic_v1.method_async.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=None, client_info=client_info, ), - self.delete_instance: gapic_v1.method_async.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=None, client_info=client_info, ), - self.import_data: gapic_v1.method_async.wrap_method( + self.import_data: self._wrap_method( self.import_data, default_timeout=None, client_info=client_info, ), - self.export_data: gapic_v1.method_async.wrap_method( + self.export_data: self._wrap_method( self.export_data, default_timeout=None, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest.py index 928252b84ce3..8e07bc1068b5 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.parallelstore_v1.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseParallelstoreRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.parallelstore_v1.types import parallelstore - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ParallelstoreTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -437,8 +427,8 @@ class ParallelstoreRestStub: _interceptor: ParallelstoreRestInterceptor -class ParallelstoreRestTransport(ParallelstoreTransport): - """REST backend transport for Parallelstore. +class ParallelstoreRestTransport(_BaseParallelstoreRestTransport): + """REST backend synchronous transport for Parallelstore. Service describing handlers for resources Configures and manages parallelstore resources. @@ -467,7 +457,6 @@ class ParallelstoreRestTransport(ParallelstoreTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -521,21 +510,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -600,21 +580,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateInstance(ParallelstoreRestStub): + class _CreateInstance( + _BaseParallelstoreRestTransport._BaseCreateInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("CreateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "instanceId": "", - } - - @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 - } + return hash("ParallelstoreRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -643,45 +636,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/instances", - "body": "instance", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - pb_request = parallelstore.CreateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseParallelstoreRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseParallelstoreRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -695,19 +675,33 @@ def __call__( resp = self._interceptor.post_create_instance(resp) return resp - class _DeleteInstance(ParallelstoreRestStub): + class _DeleteInstance( + _BaseParallelstoreRestTransport._BaseDeleteInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("DeleteInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -736,38 +730,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - pb_request = parallelstore.DeleteInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -781,19 +764,34 @@ def __call__( resp = self._interceptor.post_delete_instance(resp) return resp - class _ExportData(ParallelstoreRestStub): + class _ExportData( + _BaseParallelstoreRestTransport._BaseExportData, ParallelstoreRestStub + ): def __hash__(self): - return hash("ExportData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ExportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -823,45 +821,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:exportData", - "body": "*", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseExportData._get_http_options() + ) request, metadata = self._interceptor.pre_export_data(request, metadata) - pb_request = parallelstore.ExportDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseParallelstoreRestTransport._BaseExportData._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseParallelstoreRestTransport._BaseExportData._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseExportData._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._ExportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -875,19 +866,33 @@ def __call__( resp = self._interceptor.post_export_data(resp) return resp - class _GetInstance(ParallelstoreRestStub): + class _GetInstance( + _BaseParallelstoreRestTransport._BaseGetInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("GetInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -913,38 +918,29 @@ def __call__( A Parallelstore instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - pb_request = parallelstore.GetInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -960,19 +956,34 @@ def __call__( resp = self._interceptor.post_get_instance(resp) return resp - class _ImportData(ParallelstoreRestStub): + class _ImportData( + _BaseParallelstoreRestTransport._BaseImportData, ParallelstoreRestStub + ): def __hash__(self): - return hash("ImportData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ImportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1002,45 +1013,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:importData", - "body": "*", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseImportData._get_http_options() + ) request, metadata = self._interceptor.pre_import_data(request, metadata) - pb_request = parallelstore.ImportDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseParallelstoreRestTransport._BaseImportData._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseParallelstoreRestTransport._BaseImportData._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseImportData._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._ImportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1054,19 +1058,33 @@ def __call__( resp = self._interceptor.post_import_data(resp) return resp - class _ListInstances(ParallelstoreRestStub): + class _ListInstances( + _BaseParallelstoreRestTransport._BaseListInstances, ParallelstoreRestStub + ): def __hash__(self): - return hash("ListInstances") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1094,38 +1112,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/instances", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - pb_request = parallelstore.ListInstancesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseListInstances._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1141,21 +1148,34 @@ def __call__( resp = self._interceptor.post_list_instances(resp) return resp - class _UpdateInstance(ParallelstoreRestStub): + class _UpdateInstance( + _BaseParallelstoreRestTransport._BaseUpdateInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("UpdateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("ParallelstoreRestTransport.UpdateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1184,45 +1204,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{instance.name=projects/*/locations/*/instances/*}", - "body": "instance", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - pb_request = parallelstore.UpdateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1298,7 +1305,34 @@ def update_instance( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(ParallelstoreRestStub): + class _GetLocation( + _BaseParallelstoreRestTransport._BaseGetLocation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1322,32 +1356,29 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseParallelstoreRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ParallelstoreRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1355,8 +1386,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1364,7 +1396,34 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(ParallelstoreRestStub): + class _ListLocations( + _BaseParallelstoreRestTransport._BaseListLocations, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1388,32 +1447,27 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1421,8 +1475,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1430,7 +1485,35 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(ParallelstoreRestStub): + class _CancelOperation( + _BaseParallelstoreRestTransport._BaseCancelOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1451,37 +1534,34 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseParallelstoreRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseParallelstoreRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = ParallelstoreRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1495,7 +1575,34 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(ParallelstoreRestStub): + class _DeleteOperation( + _BaseParallelstoreRestTransport._BaseDeleteOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1516,34 +1623,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1557,7 +1659,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ParallelstoreRestStub): + class _GetOperation( + _BaseParallelstoreRestTransport._BaseGetOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1581,32 +1710,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1614,8 +1738,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1623,7 +1748,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ParallelstoreRestStub): + class _ListOperations( + _BaseParallelstoreRestTransport._BaseListOperations, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1647,32 +1799,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1680,8 +1827,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest_base.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest_base.py new file mode 100644 index 000000000000..ae740189c043 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1/services/parallelstore/transports/rest_base.py @@ -0,0 +1,622 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.parallelstore_v1.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO, ParallelstoreTransport + + +class _BaseParallelstoreRestTransport(ParallelstoreTransport): + """Base REST backend transport for Parallelstore. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "parallelstore.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseCreateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseDeleteInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:exportData", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ExportDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseExportData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:importData", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ImportDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseImportData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.UpdateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseUpdateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseParallelstoreRestTransport",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py index 668eac0d72ce..558c8aab67c5 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py index af354b4aee21..c91c4594822a 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py @@ -1171,11 +1171,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1228,11 +1224,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1289,11 +1281,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1346,11 +1334,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1400,11 +1384,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1457,11 +1437,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py index 03db0bc0e5c8..8d9f0a550a3c 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py @@ -1639,11 +1639,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1696,11 +1692,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1757,11 +1749,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1814,11 +1802,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1868,11 +1852,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1925,11 +1905,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/README.rst b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/README.rst new file mode 100644 index 000000000000..5b77d01587ad --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ParallelstoreTransport` is the ABC for all transports. +- public child `ParallelstoreGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ParallelstoreGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseParallelstoreRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ParallelstoreRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py index e263205b5290..0ec8a767f68c 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py @@ -165,6 +165,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py index 9a243a8a7c83..05b70a49fd18 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -249,6 +250,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -478,46 +482,85 @@ def export_data( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=None, client_info=client_info, ), - self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=None, client_info=client_info, ), - self.create_instance: gapic_v1.method_async.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=None, client_info=client_info, ), - self.update_instance: gapic_v1.method_async.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=None, client_info=client_info, ), - self.delete_instance: gapic_v1.method_async.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=None, client_info=client_info, ), - self.import_data: gapic_v1.method_async.wrap_method( + self.import_data: self._wrap_method( self.import_data, default_timeout=None, client_info=client_info, ), - self.export_data: gapic_v1.method_async.wrap_method( + self.export_data: self._wrap_method( self.export_data, default_timeout=None, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py index ff9e16346f08..9273ead5a371 100644 --- a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseParallelstoreRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.parallelstore_v1beta.types import parallelstore - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ParallelstoreTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -437,8 +427,8 @@ class ParallelstoreRestStub: _interceptor: ParallelstoreRestInterceptor -class ParallelstoreRestTransport(ParallelstoreTransport): - """REST backend transport for Parallelstore. +class ParallelstoreRestTransport(_BaseParallelstoreRestTransport): + """REST backend synchronous transport for Parallelstore. Service describing handlers for resources Configures and manages parallelstore resources. @@ -467,7 +457,6 @@ class ParallelstoreRestTransport(ParallelstoreTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -521,21 +510,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -600,21 +580,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateInstance(ParallelstoreRestStub): + class _CreateInstance( + _BaseParallelstoreRestTransport._BaseCreateInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("CreateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "instanceId": "", - } - - @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 - } + return hash("ParallelstoreRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -643,45 +636,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta/{parent=projects/*/locations/*}/instances", - "body": "instance", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - pb_request = parallelstore.CreateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseParallelstoreRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseParallelstoreRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -695,19 +675,33 @@ def __call__( resp = self._interceptor.post_create_instance(resp) return resp - class _DeleteInstance(ParallelstoreRestStub): + class _DeleteInstance( + _BaseParallelstoreRestTransport._BaseDeleteInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("DeleteInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -736,38 +730,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - pb_request = parallelstore.DeleteInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -781,19 +764,34 @@ def __call__( resp = self._interceptor.post_delete_instance(resp) return resp - class _ExportData(ParallelstoreRestStub): + class _ExportData( + _BaseParallelstoreRestTransport._BaseExportData, ParallelstoreRestStub + ): def __hash__(self): - return hash("ExportData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ExportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -823,45 +821,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:exportData", - "body": "*", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseExportData._get_http_options() + ) request, metadata = self._interceptor.pre_export_data(request, metadata) - pb_request = parallelstore.ExportDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseParallelstoreRestTransport._BaseExportData._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseParallelstoreRestTransport._BaseExportData._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseExportData._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._ExportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -875,19 +866,33 @@ def __call__( resp = self._interceptor.post_export_data(resp) return resp - class _GetInstance(ParallelstoreRestStub): + class _GetInstance( + _BaseParallelstoreRestTransport._BaseGetInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("GetInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -913,38 +918,29 @@ def __call__( A Parallelstore instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - pb_request = parallelstore.GetInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -960,19 +956,34 @@ def __call__( resp = self._interceptor.post_get_instance(resp) return resp - class _ImportData(ParallelstoreRestStub): + class _ImportData( + _BaseParallelstoreRestTransport._BaseImportData, ParallelstoreRestStub + ): def __hash__(self): - return hash("ImportData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ImportData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1002,45 +1013,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:importData", - "body": "*", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseImportData._get_http_options() + ) request, metadata = self._interceptor.pre_import_data(request, metadata) - pb_request = parallelstore.ImportDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseParallelstoreRestTransport._BaseImportData._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseParallelstoreRestTransport._BaseImportData._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseParallelstoreRestTransport._BaseImportData._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._ImportData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1054,19 +1058,33 @@ def __call__( resp = self._interceptor.post_import_data(resp) return resp - class _ListInstances(ParallelstoreRestStub): + class _ListInstances( + _BaseParallelstoreRestTransport._BaseListInstances, ParallelstoreRestStub + ): def __hash__(self): - return hash("ListInstances") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ParallelstoreRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1094,38 +1112,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{parent=projects/*/locations/*}/instances", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - pb_request = parallelstore.ListInstancesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseListInstances._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ParallelstoreRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1141,21 +1148,34 @@ def __call__( resp = self._interceptor.post_list_instances(resp) return resp - class _UpdateInstance(ParallelstoreRestStub): + class _UpdateInstance( + _BaseParallelstoreRestTransport._BaseUpdateInstance, ParallelstoreRestStub + ): def __hash__(self): - return hash("UpdateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("ParallelstoreRestTransport.UpdateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1184,45 +1204,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta/{instance.name=projects/*/locations/*/instances/*}", - "body": "instance", - }, - ] + http_options = ( + _BaseParallelstoreRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - pb_request = parallelstore.UpdateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseParallelstoreRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ParallelstoreRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1298,7 +1305,34 @@ def update_instance( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(ParallelstoreRestStub): + class _GetLocation( + _BaseParallelstoreRestTransport._BaseGetLocation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1322,32 +1356,29 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseParallelstoreRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ParallelstoreRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1355,8 +1386,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1364,7 +1396,34 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(ParallelstoreRestStub): + class _ListLocations( + _BaseParallelstoreRestTransport._BaseListLocations, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1388,32 +1447,27 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1421,8 +1475,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1430,7 +1485,35 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(ParallelstoreRestStub): + class _CancelOperation( + _BaseParallelstoreRestTransport._BaseCancelOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1451,37 +1534,34 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseParallelstoreRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseParallelstoreRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = ParallelstoreRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1495,7 +1575,34 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(ParallelstoreRestStub): + class _DeleteOperation( + _BaseParallelstoreRestTransport._BaseDeleteOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1516,34 +1623,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1557,7 +1659,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ParallelstoreRestStub): + class _GetOperation( + _BaseParallelstoreRestTransport._BaseGetOperation, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1581,32 +1710,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1614,8 +1738,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1623,7 +1748,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ParallelstoreRestStub): + class _ListOperations( + _BaseParallelstoreRestTransport._BaseListOperations, ParallelstoreRestStub + ): + def __hash__(self): + return hash("ParallelstoreRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1647,32 +1799,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseParallelstoreRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseParallelstoreRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseParallelstoreRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ParallelstoreRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1680,8 +1827,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest_base.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest_base.py new file mode 100644 index 000000000000..b9f897a71278 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest_base.py @@ -0,0 +1,622 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO, ParallelstoreTransport + + +class _BaseParallelstoreRestTransport(ParallelstoreTransport): + """Base REST backend transport for Parallelstore. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "parallelstore.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseCreateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseDeleteInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:exportData", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ExportDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseExportData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:importData", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ImportDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseImportData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = parallelstore.UpdateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseParallelstoreRestTransport._BaseUpdateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseParallelstoreRestTransport",) diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1.json b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1.json index f239bf8e8263..aec0635b88a7 100644 --- a/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1.json +++ b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-parallelstore", - "version": "0.2.4" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json index 9df78079c0fa..01334a8f8053 100644 --- a/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json +++ b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-parallelstore", - "version": "0.2.4" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-parallelstore/setup.py b/packages/google-cloud-parallelstore/setup.py index 56d3bc3d4cd7..26284b41af71 100644 --- a/packages/google-cloud-parallelstore/setup.py +++ b/packages/google-cloud-parallelstore/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1/test_parallelstore.py b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1/test_parallelstore.py index 8f1b10a1e2e9..88c3c1011bd2 100644 --- a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1/test_parallelstore.py +++ b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1/test_parallelstore.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,15 +64,7 @@ from google.oauth2 import service_account from google.protobuf import empty_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 -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.parallelstore_v1.services.parallelstore import ( ParallelstoreAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.parallelstore_v1.types import parallelstore +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1165,25 +1188,6 @@ def test_list_instances(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_instances_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ListInstancesRequest() - - def test_list_instances_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1253,30 +1257,6 @@ def test_list_instances_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_instances_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - parallelstore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ListInstancesRequest() - - @pytest.mark.asyncio async def test_list_instances_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1285,7 +1265,7 @@ async def test_list_instances_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1324,7 +1304,7 @@ async def test_list_instances_async( transport: str = "grpc_asyncio", request_type=parallelstore.ListInstancesRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1392,7 +1372,7 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,7 +1442,7 @@ def test_list_instances_flattened_error(): @pytest.mark.asyncio async def test_list_instances_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1491,7 +1471,7 @@ async def test_list_instances_flattened_async(): @pytest.mark.asyncio async def test_list_instances_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1601,7 +1581,7 @@ def test_list_instances_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_instances_async_pager(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1651,7 +1631,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1759,25 +1739,6 @@ def test_get_instance(request_type, transport: str = "grpc"): ) -def test_get_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.GetInstanceRequest() - - def test_get_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1841,39 +1802,6 @@ def test_get_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - parallelstore.Instance( - name="name_value", - description="description_value", - state=parallelstore.Instance.State.CREATING, - capacity_gib=1247, - daos_version="daos_version_value", - access_points=["access_points_value"], - network="network_value", - reserved_ip_range="reserved_ip_range_value", - effective_reserved_ip_range="effective_reserved_ip_range_value", - file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, - directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, - ) - ) - response = await client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.GetInstanceRequest() - - @pytest.mark.asyncio async def test_get_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1882,7 +1810,7 @@ async def test_get_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1921,7 +1849,7 @@ async def test_get_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.GetInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2013,7 +1941,7 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2083,7 +2011,7 @@ def test_get_instance_flattened_error(): @pytest.mark.asyncio async def test_get_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2112,7 +2040,7 @@ async def test_get_instance_flattened_async(): @pytest.mark.asyncio async def test_get_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2157,25 +2085,6 @@ def test_create_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.CreateInstanceRequest() - - def test_create_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2248,27 +2157,6 @@ def test_create_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.CreateInstanceRequest() - - @pytest.mark.asyncio async def test_create_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2277,7 +2165,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2321,7 +2209,7 @@ async def test_create_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.CreateInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2384,7 +2272,7 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio async def test_create_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2464,7 +2352,7 @@ def test_create_instance_flattened_error(): @pytest.mark.asyncio async def test_create_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2501,7 +2389,7 @@ async def test_create_instance_flattened_async(): @pytest.mark.asyncio async def test_create_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2548,25 +2436,6 @@ def test_update_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.UpdateInstanceRequest() - - def test_update_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2635,27 +2504,6 @@ def test_update_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.UpdateInstanceRequest() - - @pytest.mark.asyncio async def test_update_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2664,7 +2512,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2708,7 +2556,7 @@ async def test_update_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.UpdateInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2771,7 +2619,7 @@ def test_update_instance_field_headers(): @pytest.mark.asyncio async def test_update_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2846,7 +2694,7 @@ def test_update_instance_flattened_error(): @pytest.mark.asyncio async def test_update_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2879,7 +2727,7 @@ async def test_update_instance_flattened_async(): @pytest.mark.asyncio async def test_update_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2925,25 +2773,6 @@ def test_delete_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.DeleteInstanceRequest() - - def test_delete_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3014,27 +2843,6 @@ def test_delete_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.DeleteInstanceRequest() - - @pytest.mark.asyncio async def test_delete_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3043,7 +2851,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3087,7 +2895,7 @@ async def test_delete_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.DeleteInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3150,7 +2958,7 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3220,7 +3028,7 @@ def test_delete_instance_flattened_error(): @pytest.mark.asyncio async def test_delete_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3249,7 +3057,7 @@ async def test_delete_instance_flattened_async(): @pytest.mark.asyncio async def test_delete_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3294,25 +3102,6 @@ def test_import_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ImportDataRequest() - - def test_import_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3383,27 +3172,6 @@ def test_import_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ImportDataRequest() - - @pytest.mark.asyncio async def test_import_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3412,7 +3180,7 @@ async def test_import_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3456,7 +3224,7 @@ async def test_import_data_async( transport: str = "grpc_asyncio", request_type=parallelstore.ImportDataRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3519,7 +3287,7 @@ def test_import_data_field_headers(): @pytest.mark.asyncio async def test_import_data_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3581,28 +3349,9 @@ def test_export_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ExportDataRequest() - - -def test_export_data_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_export_data_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -3670,27 +3419,6 @@ def test_export_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ExportDataRequest() - - @pytest.mark.asyncio async def test_export_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3699,7 +3427,7 @@ async def test_export_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3743,7 +3471,7 @@ async def test_export_data_async( transport: str = "grpc_asyncio", request_type=parallelstore.ExportDataRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3806,7 +3534,7 @@ def test_export_data_field_headers(): @pytest.mark.asyncio async def test_export_data_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3835,48 +3563,6 @@ async def test_export_data_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest(request_type): - client = ParallelstoreClient( - 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 = parallelstore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = parallelstore.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_instances(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_instances_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4015,87 +3701,6 @@ def test_list_instances_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_list_instances" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_list_instances" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ListInstancesRequest.pb( - parallelstore.ListInstancesRequest() - ) - 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 = parallelstore.ListInstancesResponse.to_json( - parallelstore.ListInstancesResponse() - ) - - request = parallelstore.ListInstancesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = parallelstore.ListInstancesResponse() - - client.list_instances( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ListInstancesRequest -): - client = ParallelstoreClient( - 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.list_instances(request) - - def test_list_instances_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4215,72 +3820,6 @@ def test_list_instances_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.GetInstanceRequest, - dict, - ], -) -def test_get_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = parallelstore.Instance( - name="name_value", - description="description_value", - state=parallelstore.Instance.State.CREATING, - capacity_gib=1247, - daos_version="daos_version_value", - access_points=["access_points_value"], - network="network_value", - reserved_ip_range="reserved_ip_range_value", - effective_reserved_ip_range="effective_reserved_ip_range_value", - file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, - directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = parallelstore.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, parallelstore.Instance) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == parallelstore.Instance.State.CREATING - assert response.capacity_gib == 1247 - assert response.daos_version == "daos_version_value" - assert response.access_points == ["access_points_value"] - assert response.network == "network_value" - assert response.reserved_ip_range == "reserved_ip_range_value" - assert response.effective_reserved_ip_range == "effective_reserved_ip_range_value" - assert ( - response.file_stripe_level - == parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN - ) - assert ( - response.directory_stripe_level - == parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN - ) - - def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4400,97 +3939,16 @@ def test_get_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_get_instance_rest_flattened(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), + transport="rest", ) - client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_get_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_get_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.GetInstanceRequest.pb( - parallelstore.GetInstanceRequest() - ) - 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 = parallelstore.Instance.to_json( - parallelstore.Instance() - ) - - request = parallelstore.GetInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = parallelstore.Instance() - - client.get_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.GetInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance(request) - - -def test_get_instance_rest_flattened(): - client = ParallelstoreClient( - 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 = parallelstore.Instance() + # 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 = parallelstore.Instance() # get arguments that satisfy an http rule for this method sample_request = { @@ -4539,130 +3997,6 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.CreateInstanceRequest, - dict, - ], -) -def test_create_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "description": "description_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "capacity_gib": 1247, - "daos_version": "daos_version_value", - "access_points": ["access_points_value1", "access_points_value2"], - "network": "network_value", - "reserved_ip_range": "reserved_ip_range_value", - "effective_reserved_ip_range": "effective_reserved_ip_range_value", - "file_stripe_level": 1, - "directory_stripe_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = parallelstore.CreateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4818,89 +4152,6 @@ def test_create_instance_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_create_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_create_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.CreateInstanceRequest.pb( - parallelstore.CreateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.CreateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.CreateInstanceRequest -): - client = ParallelstoreClient( - 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.create_instance(request) - - def test_create_instance_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4959,132 +4210,6 @@ def test_create_instance_rest_flattened_error(transport: str = "rest"): ) -def test_create_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.UpdateInstanceRequest, - dict, - ], -) -def test_update_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "description": "description_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "capacity_gib": 1247, - "daos_version": "daos_version_value", - "access_points": ["access_points_value1", "access_points_value2"], - "network": "network_value", - "reserved_ip_range": "reserved_ip_range_value", - "effective_reserved_ip_range": "effective_reserved_ip_range_value", - "file_stripe_level": 1, - "directory_stripe_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = parallelstore.UpdateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5221,91 +4346,6 @@ def test_update_instance_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_update_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_update_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.UpdateInstanceRequest.pb( - parallelstore.UpdateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.UpdateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.UpdateInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/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.update_instance(request) - - def test_update_instance_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5365,47 +4405,6 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): ) -def test_update_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.DeleteInstanceRequest, - dict, - ], -) -def test_delete_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5528,93 +4527,10 @@ def test_delete_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_delete_instance_rest_flattened(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_delete_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_delete_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.DeleteInstanceRequest.pb( - parallelstore.DeleteInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.DeleteInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.DeleteInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.delete_instance(request) - - -def test_delete_instance_rest_flattened(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5667,47 +4583,6 @@ def test_delete_instance_rest_flattened_error(transport: str = "rest"): ) -def test_delete_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ImportDataRequest, - dict, - ], -) -def test_import_data_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5827,130 +4702,6 @@ def test_import_data_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_data_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_import_data" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_import_data" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ImportDataRequest.pb( - parallelstore.ImportDataRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.ImportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_data_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ImportDataRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.import_data(request) - - -def test_import_data_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ExportDataRequest, - dict, - ], -) -def test_export_data_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6070,104 +4821,15 @@ def test_export_data_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_data_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ParallelstoreGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_export_data" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_export_data" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ExportDataRequest.pb( - parallelstore.ExportDataRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.ExportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_data_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ExportDataRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.export_data(request) - - -def test_export_data_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ParallelstoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + with pytest.raises(ValueError): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -6251,1109 +4913,2617 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ParallelstoreClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = ParallelstoreClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.kind == transport_name + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = parallelstore.ListInstancesResponse() + client.list_instances(request=None) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert isinstance( - client.transport, - transports.ParallelstoreGrpcTransport, + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = parallelstore.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) -def test_parallelstore_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ParallelstoreTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.ParallelstoreTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_instances", - "get_instance", - "create_instance", - "update_instance", - "delete_instance", - "import_data", - "export_data", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_parallelstore_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.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParallelstoreTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) -def test_parallelstore_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParallelstoreTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParallelstoreClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_data(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - transports.ParallelstoreRestTransport, - ], -) -def test_parallelstore_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParallelstoreGrpcTransport, grpc_helpers), - (transports.ParallelstoreGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_parallelstore_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "parallelstore.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="parallelstore.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_data(request=None) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + assert args[0] == request_msg -def test_parallelstore_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.ParallelstoreRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) +def test_transport_kind_grpc_asyncio(): + transport = ParallelstoreAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" -def test_parallelstore_rest_lro_client(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_initialize_client_w_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - transport = client.transport + assert client is not None - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_parallelstore_host_no_port(transport_name): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="parallelstore.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "parallelstore.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://parallelstore.googleapis.com" - ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_parallelstore_host_with_port(transport_name): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="parallelstore.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "parallelstore.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://parallelstore.googleapis.com:8000" +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + effective_reserved_ip_range="effective_reserved_ip_range_value", + file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, + directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, + ) + ) + await client.get_instance(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_parallelstore_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ParallelstoreClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ParallelstoreClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_instances._session - session2 = client2.transport.list_instances._session - assert session1 != session2 - session1 = client1.transport.get_instance._session - session2 = client2.transport.get_instance._session - assert session1 != session2 - session1 = client1.transport.create_instance._session - session2 = client2.transport.create_instance._session - assert session1 != session2 - session1 = client1.transport.update_instance._session - session2 = client2.transport.update_instance._session - assert session1 != session2 - session1 = client1.transport.delete_instance._session - session2 = client2.transport.delete_instance._session - assert session1 != session2 - session1 = client1.transport.import_data._session - session2 = client2.transport.import_data._session - assert session1 != session2 - session1 = client1.transport.export_data._session - session2 = client2.transport.export_data._session - assert session1 != session2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.ParallelstoreGrpcTransport( - host="squid.clam.whelk", - channel=channel, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) -def test_parallelstore_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() - # Check that channel is used if provided. - transport = transports.ParallelstoreGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + assert args[0] == request_msg - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + assert args[0] == request_msg -def test_parallelstore_grpc_lro_client(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_data_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_data(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() + assert args[0] == request_msg -def test_parallelstore_grpc_lro_async_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_data_empty_call_grpc_asyncio(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_data(request=None) -def test_address_path(): - project = "squid" - region = "clam" - address = "whelk" - expected = "projects/{project}/regions/{region}/addresses/{address}".format( - project=project, - region=region, - address=address, - ) - actual = ParallelstoreClient.address_path(project, region, address) - assert expected == actual + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() + assert args[0] == request_msg -def test_parse_address_path(): - expected = { - "project": "octopus", - "region": "oyster", - "address": "nudibranch", - } - path = ParallelstoreClient.address_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_address_path(path) - assert expected == actual +def test_transport_kind_rest(): + transport = ParallelstoreClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" -def test_instance_path(): - project = "cuttlefish" - location = "mussel" - instance = "winkle" - expected = "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, +def test_list_instances_rest_bad_request( + request_type=parallelstore.ListInstancesRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.instance_path(project, location, instance) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_instances(request) -def test_parse_instance_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", - } - path = ParallelstoreClient.instance_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_instance_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = ParallelstoreClient( + 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) -def test_network_path(): - project = "squid" - network = "clam" - expected = "projects/{project}/global/networks/{network}".format( - project=project, - network=network, - ) - actual = ParallelstoreClient.network_path(project, network) - assert expected == actual + # 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 = parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_parse_network_path(): - expected = { - "project": "whelk", - "network": "octopus", - } - path = ParallelstoreClient.network_path(**expected) + # Convert return value to protobuf type + return_value = parallelstore.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_instances(request) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_network_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_service_account_path(): - project = "oyster" - service_account = "nudibranch" - expected = "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), ) - actual = ParallelstoreClient.service_account_path(project, service_account) - assert expected == actual + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ListInstancesRequest.pb( + parallelstore.ListInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_parse_service_account_path(): - expected = { - "project": "cuttlefish", - "service_account": "mussel", - } - path = ParallelstoreClient.service_account_path(**expected) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = parallelstore.ListInstancesResponse.to_json( + parallelstore.ListInstancesResponse() + ) + req.return_value.content = return_value - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_service_account_path(path) - assert expected == actual + request = parallelstore.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.ListInstancesResponse() + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = ParallelstoreClient.common_billing_account_path(billing_account) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ParallelstoreClient.common_billing_account_path(**expected) +def test_get_instance_rest_bad_request(request_type=parallelstore.GetInstanceRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_billing_account_path(path) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance(request) -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.common_folder_path(folder) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ParallelstoreClient.common_folder_path(**expected) + # 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 = parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + effective_reserved_ip_range="effective_reserved_ip_range_value", + file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, + directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, + ) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_folder_path(path) - assert expected == actual + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = parallelstore.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance(request) -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, + # Establish that the response is the type that we expect. + assert isinstance(response, parallelstore.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == parallelstore.Instance.State.CREATING + assert response.capacity_gib == 1247 + assert response.daos_version == "daos_version_value" + assert response.access_points == ["access_points_value"] + assert response.network == "network_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + assert response.effective_reserved_ip_range == "effective_reserved_ip_range_value" + assert ( + response.file_stripe_level + == parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN + ) + assert ( + response.directory_stripe_level + == parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN ) - actual = ParallelstoreClient.common_organization_path(organization) - assert expected == actual - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ParallelstoreClient.common_organization_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_organization_path(path) - assert expected == actual +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.GetInstanceRequest.pb( + parallelstore.GetInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format( - project=project, - ) - actual = ParallelstoreClient.common_project_path(project) - assert expected == actual + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = parallelstore.Instance.to_json(parallelstore.Instance()) + req.return_value.content = return_value + request = parallelstore.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.Instance() -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ParallelstoreClient.common_project_path(**expected) + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_project_path(path) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +def test_create_instance_rest_bad_request( + request_type=parallelstore.CreateInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.common_location_path(project, location) - assert expected == actual - + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ParallelstoreClient.common_location_path(**expected) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_instance(request) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_location_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_value", + "effective_reserved_ip_range": "effective_reserved_ip_range_value", + "file_stripe_level": 1, + "directory_stripe_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = parallelstore.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) with mock.patch.object( - transports.ParallelstoreTransport, "_prep_wrapped_messages" - ) as prep: - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.CreateInstanceRequest.pb( + parallelstore.CreateInstanceRequest() ) - prep.assert_called_once_with(client_info) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - with mock.patch.object( - transports.ParallelstoreTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = ParallelstoreClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - prep.assert_called_once_with(client_info) + pre.assert_called_once() + post.assert_called_once() -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + +def test_update_instance_rest_bad_request( + request_type=parallelstore.UpdateInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_value", + "effective_reserved_ip_range": "effective_reserved_ip_range_value", + "file_stripe_level": 1, + "directory_stripe_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = parallelstore.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.UpdateInstanceRequest.pb( + parallelstore.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=parallelstore.DeleteInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_delete_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.DeleteInstanceRequest.pb( + parallelstore.DeleteInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_data_rest_bad_request(request_type=parallelstore.ImportDataRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ImportDataRequest, + dict, + ], +) +def test_import_data_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_data_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_import_data" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_import_data" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ImportDataRequest.pb( + parallelstore.ImportDataRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.ImportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_data_rest_bad_request(request_type=parallelstore.ExportDataRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ExportDataRequest, + dict, + ], +) +def test_export_data_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_data_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_export_data" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_export_data" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ExportDataRequest.pb( + parallelstore.ExportDataRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.ExportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + client.import_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + client.export_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() + + assert args[0] == request_msg + + +def test_parallelstore_rest_lro_client(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ParallelstoreGrpcTransport, + ) + + +def test_parallelstore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_parallelstore_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_instances", + "get_instance", + "create_instance", + "update_instance", + "delete_instance", + "import_data", + "export_data", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_parallelstore_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.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_parallelstore_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.parallelstore_v1.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport() + adc.assert_called_once() + + +def test_parallelstore_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParallelstoreClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + transports.ParallelstoreRestTransport, + ], +) +def test_parallelstore_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParallelstoreGrpcTransport, grpc_helpers), + (transports.ParallelstoreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_parallelstore_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "parallelstore.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="parallelstore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_parallelstore_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.ParallelstoreRestTransport( + 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_parallelstore_host_no_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_parallelstore_host_with_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_parallelstore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ParallelstoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ParallelstoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.import_data._session + session2 = client2.transport.import_data._session + assert session1 != session2 + session1 = client1.transport.export_data._session + session2 = client2.transport.export_data._session + assert session1 != session2 + + +def test_parallelstore_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_parallelstore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest -): +def test_parallelstore_grpc_lro_client(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - # 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_location(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.GetLocationRequest, - dict, - ], -) -def test_get_location_rest(request_type): - client = ParallelstoreClient( +def test_parallelstore_grpc_lro_async_client(): + client = ParallelstoreAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc_asyncio", ) - request_init = {"name": "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 = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + transport = client.transport - response = client.get_location(request) + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_address_path(): + project = "squid" + region = "clam" + address = "whelk" + expected = "projects/{project}/regions/{region}/addresses/{address}".format( + project=project, + region=region, + address=address, ) + actual = ParallelstoreClient.address_path(project, region, address) + assert expected == actual - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - - # 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.list_locations(request) +def test_parse_address_path(): + expected = { + "project": "octopus", + "region": "oyster", + "address": "nudibranch", + } + path = ParallelstoreClient.address_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_address_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_instance_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = ParallelstoreClient.instance_path(project, location, instance) + assert expected == actual - response = client.list_locations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) +def test_parse_instance_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "instance": "abalone", + } + path = ParallelstoreClient.instance_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_instance_path(path) + assert expected == actual -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_network_path(): + project = "squid" + network = "clam" + expected = "projects/{project}/global/networks/{network}".format( + project=project, + network=network, ) + actual = ParallelstoreClient.network_path(project, network) + assert expected == actual - # 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.cancel_operation(request) +def test_parse_network_path(): + expected = { + "project": "whelk", + "network": "octopus", + } + path = ParallelstoreClient.network_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_network_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_service_account_path(): + project = "oyster" + service_account = "nudibranch" + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + actual = ParallelstoreClient.service_account_path(project, service_account) + assert expected == actual - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_parse_service_account_path(): + expected = { + "project": "cuttlefish", + "service_account": "mussel", + } + path = ParallelstoreClient.service_account_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_service_account_path(path) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - - # 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.delete_operation(request) + actual = ParallelstoreClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ParallelstoreClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ParallelstoreClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ParallelstoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_folder_path(path) + assert expected == actual -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = ParallelstoreClient.common_organization_path(organization) + assert expected == actual - # 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_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ParallelstoreClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = ParallelstoreClient.common_project_path(project) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ParallelstoreClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_project_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = ParallelstoreClient.common_location_path(project, location) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ParallelstoreClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.list_operations(request) + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ParallelstoreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -7383,7 +7553,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7436,7 +7606,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7481,7 +7651,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -7522,7 +7692,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7575,7 +7745,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7620,7 +7790,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -7661,7 +7831,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7716,7 +7886,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7763,7 +7933,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -7806,7 +7976,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7861,7 +8031,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7908,7 +8078,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -7951,7 +8121,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8006,7 +8176,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8053,7 +8223,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -8096,7 +8266,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8148,7 +8318,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = ParallelstoreAsyncClient(credentials=ga_credentials.AnonymousCredentials()) + client = ParallelstoreAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -8194,7 +8364,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -8210,22 +8380,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py index 6d759022cccf..cc23fb4cec79 100644 --- a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py +++ b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,15 +64,7 @@ from google.oauth2 import service_account from google.protobuf import empty_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 -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.parallelstore_v1beta.services.parallelstore import ( ParallelstoreAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.parallelstore_v1beta.types import parallelstore +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1165,25 +1188,6 @@ def test_list_instances(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_instances_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ListInstancesRequest() - - def test_list_instances_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1253,30 +1257,6 @@ def test_list_instances_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_instances_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - parallelstore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ListInstancesRequest() - - @pytest.mark.asyncio async def test_list_instances_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1285,7 +1265,7 @@ async def test_list_instances_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1324,7 +1304,7 @@ async def test_list_instances_async( transport: str = "grpc_asyncio", request_type=parallelstore.ListInstancesRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1392,7 +1372,7 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,7 +1442,7 @@ def test_list_instances_flattened_error(): @pytest.mark.asyncio async def test_list_instances_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1491,7 +1471,7 @@ async def test_list_instances_flattened_async(): @pytest.mark.asyncio async def test_list_instances_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1601,7 +1581,7 @@ def test_list_instances_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_instances_async_pager(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1651,7 +1631,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1759,25 +1739,6 @@ def test_get_instance(request_type, transport: str = "grpc"): ) -def test_get_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.GetInstanceRequest() - - def test_get_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1841,39 +1802,6 @@ def test_get_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - parallelstore.Instance( - name="name_value", - description="description_value", - state=parallelstore.Instance.State.CREATING, - capacity_gib=1247, - daos_version="daos_version_value", - access_points=["access_points_value"], - network="network_value", - reserved_ip_range="reserved_ip_range_value", - effective_reserved_ip_range="effective_reserved_ip_range_value", - file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, - directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, - ) - ) - response = await client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.GetInstanceRequest() - - @pytest.mark.asyncio async def test_get_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1882,7 +1810,7 @@ async def test_get_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1921,7 +1849,7 @@ async def test_get_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.GetInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2013,7 +1941,7 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2083,7 +2011,7 @@ def test_get_instance_flattened_error(): @pytest.mark.asyncio async def test_get_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2112,7 +2040,7 @@ async def test_get_instance_flattened_async(): @pytest.mark.asyncio async def test_get_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2157,25 +2085,6 @@ def test_create_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.CreateInstanceRequest() - - def test_create_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2248,27 +2157,6 @@ def test_create_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.CreateInstanceRequest() - - @pytest.mark.asyncio async def test_create_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2277,7 +2165,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2321,7 +2209,7 @@ async def test_create_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.CreateInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2384,7 +2272,7 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio async def test_create_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2464,7 +2352,7 @@ def test_create_instance_flattened_error(): @pytest.mark.asyncio async def test_create_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2501,7 +2389,7 @@ async def test_create_instance_flattened_async(): @pytest.mark.asyncio async def test_create_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2548,25 +2436,6 @@ def test_update_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.UpdateInstanceRequest() - - def test_update_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2635,27 +2504,6 @@ def test_update_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.UpdateInstanceRequest() - - @pytest.mark.asyncio async def test_update_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2664,7 +2512,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2708,7 +2556,7 @@ async def test_update_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.UpdateInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2771,7 +2619,7 @@ def test_update_instance_field_headers(): @pytest.mark.asyncio async def test_update_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2846,7 +2694,7 @@ def test_update_instance_flattened_error(): @pytest.mark.asyncio async def test_update_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2879,7 +2727,7 @@ async def test_update_instance_flattened_async(): @pytest.mark.asyncio async def test_update_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2925,25 +2773,6 @@ def test_delete_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.DeleteInstanceRequest() - - def test_delete_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3014,27 +2843,6 @@ def test_delete_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.DeleteInstanceRequest() - - @pytest.mark.asyncio async def test_delete_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3043,7 +2851,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3087,7 +2895,7 @@ async def test_delete_instance_async( transport: str = "grpc_asyncio", request_type=parallelstore.DeleteInstanceRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3150,7 +2958,7 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3220,7 +3028,7 @@ def test_delete_instance_flattened_error(): @pytest.mark.asyncio async def test_delete_instance_flattened_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3249,7 +3057,7 @@ async def test_delete_instance_flattened_async(): @pytest.mark.asyncio async def test_delete_instance_flattened_error_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3294,25 +3102,6 @@ def test_import_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ImportDataRequest() - - def test_import_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3383,27 +3172,6 @@ def test_import_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_data), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ImportDataRequest() - - @pytest.mark.asyncio async def test_import_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3412,7 +3180,7 @@ async def test_import_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3456,7 +3224,7 @@ async def test_import_data_async( transport: str = "grpc_asyncio", request_type=parallelstore.ImportDataRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3519,7 +3287,7 @@ def test_import_data_field_headers(): @pytest.mark.asyncio async def test_import_data_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3581,28 +3349,9 @@ def test_export_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ExportDataRequest() - - -def test_export_data_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_export_data_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -3670,27 +3419,6 @@ def test_export_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_data), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == parallelstore.ExportDataRequest() - - @pytest.mark.asyncio async def test_export_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3699,7 +3427,7 @@ async def test_export_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3743,7 +3471,7 @@ async def test_export_data_async( transport: str = "grpc_asyncio", request_type=parallelstore.ExportDataRequest ): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3806,7 +3534,7 @@ def test_export_data_field_headers(): @pytest.mark.asyncio async def test_export_data_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3835,48 +3563,6 @@ async def test_export_data_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest(request_type): - client = ParallelstoreClient( - 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 = parallelstore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = parallelstore.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_instances(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_instances_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4015,87 +3701,6 @@ def test_list_instances_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_list_instances" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_list_instances" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ListInstancesRequest.pb( - parallelstore.ListInstancesRequest() - ) - 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 = parallelstore.ListInstancesResponse.to_json( - parallelstore.ListInstancesResponse() - ) - - request = parallelstore.ListInstancesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = parallelstore.ListInstancesResponse() - - client.list_instances( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ListInstancesRequest -): - client = ParallelstoreClient( - 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.list_instances(request) - - def test_list_instances_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4216,72 +3821,6 @@ def test_list_instances_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.GetInstanceRequest, - dict, - ], -) -def test_get_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = parallelstore.Instance( - name="name_value", - description="description_value", - state=parallelstore.Instance.State.CREATING, - capacity_gib=1247, - daos_version="daos_version_value", - access_points=["access_points_value"], - network="network_value", - reserved_ip_range="reserved_ip_range_value", - effective_reserved_ip_range="effective_reserved_ip_range_value", - file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, - directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = parallelstore.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, parallelstore.Instance) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == parallelstore.Instance.State.CREATING - assert response.capacity_gib == 1247 - assert response.daos_version == "daos_version_value" - assert response.access_points == ["access_points_value"] - assert response.network == "network_value" - assert response.reserved_ip_range == "reserved_ip_range_value" - assert response.effective_reserved_ip_range == "effective_reserved_ip_range_value" - assert ( - response.file_stripe_level - == parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN - ) - assert ( - response.directory_stripe_level - == parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN - ) - - def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4401,97 +3940,16 @@ def test_get_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_get_instance_rest_flattened(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), + transport="rest", ) - client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_get_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_get_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.GetInstanceRequest.pb( - parallelstore.GetInstanceRequest() - ) - 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 = parallelstore.Instance.to_json( - parallelstore.Instance() - ) - - request = parallelstore.GetInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = parallelstore.Instance() - - client.get_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.GetInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance(request) - - -def test_get_instance_rest_flattened(): - client = ParallelstoreClient( - 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 = parallelstore.Instance() + # 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 = parallelstore.Instance() # get arguments that satisfy an http rule for this method sample_request = { @@ -4541,130 +3999,6 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.CreateInstanceRequest, - dict, - ], -) -def test_create_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "description": "description_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "capacity_gib": 1247, - "daos_version": "daos_version_value", - "access_points": ["access_points_value1", "access_points_value2"], - "network": "network_value", - "reserved_ip_range": "reserved_ip_range_value", - "effective_reserved_ip_range": "effective_reserved_ip_range_value", - "file_stripe_level": 1, - "directory_stripe_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = parallelstore.CreateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4820,89 +4154,6 @@ def test_create_instance_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_create_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_create_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.CreateInstanceRequest.pb( - parallelstore.CreateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.CreateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.CreateInstanceRequest -): - client = ParallelstoreClient( - 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.create_instance(request) - - def test_create_instance_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4962,132 +4213,6 @@ def test_create_instance_rest_flattened_error(transport: str = "rest"): ) -def test_create_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.UpdateInstanceRequest, - dict, - ], -) -def test_update_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "description": "description_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "capacity_gib": 1247, - "daos_version": "daos_version_value", - "access_points": ["access_points_value1", "access_points_value2"], - "network": "network_value", - "reserved_ip_range": "reserved_ip_range_value", - "effective_reserved_ip_range": "effective_reserved_ip_range_value", - "file_stripe_level": 1, - "directory_stripe_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = parallelstore.UpdateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5224,91 +4349,6 @@ def test_update_instance_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_update_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_update_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.UpdateInstanceRequest.pb( - parallelstore.UpdateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.UpdateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.UpdateInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/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.update_instance(request) - - def test_update_instance_rest_flattened(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5368,47 +4408,6 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): ) -def test_update_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.DeleteInstanceRequest, - dict, - ], -) -def test_delete_instance_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5531,93 +4530,10 @@ def test_delete_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_delete_instance_rest_flattened(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_delete_instance" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_delete_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.DeleteInstanceRequest.pb( - parallelstore.DeleteInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.DeleteInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=parallelstore.DeleteInstanceRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.delete_instance(request) - - -def test_delete_instance_rest_flattened(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5671,47 +4587,6 @@ def test_delete_instance_rest_flattened_error(transport: str = "rest"): ) -def test_delete_instance_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ImportDataRequest, - dict, - ], -) -def test_import_data_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5831,130 +4706,6 @@ def test_import_data_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_data_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), - ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_import_data" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_import_data" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ImportDataRequest.pb( - parallelstore.ImportDataRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.ImportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_data_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ImportDataRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.import_data(request) - - -def test_import_data_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - parallelstore.ExportDataRequest, - dict, - ], -) -def test_export_data_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6074,104 +4825,15 @@ def test_export_data_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_data_rest_interceptors(null_interceptor): - transport = transports.ParallelstoreRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ParallelstoreGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ParallelstoreRestInterceptor(), ) - client = ParallelstoreClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ParallelstoreRestInterceptor, "post_export_data" - ) as post, mock.patch.object( - transports.ParallelstoreRestInterceptor, "pre_export_data" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = parallelstore.ExportDataRequest.pb( - parallelstore.ExportDataRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = parallelstore.ExportDataRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_data( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_data_rest_bad_request( - transport: str = "rest", request_type=parallelstore.ExportDataRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.export_data(request) - - -def test_export_data_rest_error(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ParallelstoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + with pytest.raises(ValueError): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -6255,1109 +4917,2617 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ParallelstoreClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = ParallelstoreClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.kind == transport_name + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = parallelstore.ListInstancesResponse() + client.list_instances(request=None) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert isinstance( - client.transport, - transports.ParallelstoreGrpcTransport, + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = parallelstore.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) -def test_parallelstore_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ParallelstoreTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.ParallelstoreTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_instances", - "get_instance", - "create_instance", - "update_instance", - "delete_instance", - "import_data", - "export_data", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_parallelstore_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.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParallelstoreTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) -def test_parallelstore_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ParallelstoreTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ParallelstoreClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_data(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - transports.ParallelstoreRestTransport, - ], -) -def test_parallelstore_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ParallelstoreGrpcTransport, grpc_helpers), - (transports.ParallelstoreGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_parallelstore_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "parallelstore.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="parallelstore.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_data(request=None) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + assert args[0] == request_msg -def test_parallelstore_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.ParallelstoreRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) +def test_transport_kind_grpc_asyncio(): + transport = ParallelstoreAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" -def test_parallelstore_rest_lro_client(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_initialize_client_w_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - transport = client.transport + assert client is not None - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_parallelstore_host_no_port(transport_name): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="parallelstore.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "parallelstore.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://parallelstore.googleapis.com" - ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_parallelstore_host_with_port(transport_name): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="parallelstore.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "parallelstore.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://parallelstore.googleapis.com:8000" +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + effective_reserved_ip_range="effective_reserved_ip_range_value", + file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, + directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, + ) + ) + await client.get_instance(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_parallelstore_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ParallelstoreClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ParallelstoreClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_instances._session - session2 = client2.transport.list_instances._session - assert session1 != session2 - session1 = client1.transport.get_instance._session - session2 = client2.transport.get_instance._session - assert session1 != session2 - session1 = client1.transport.create_instance._session - session2 = client2.transport.create_instance._session - assert session1 != session2 - session1 = client1.transport.update_instance._session - session2 = client2.transport.update_instance._session - assert session1 != session2 - session1 = client1.transport.delete_instance._session - session2 = client2.transport.delete_instance._session - assert session1 != session2 - session1 = client1.transport.import_data._session - session2 = client2.transport.import_data._session - assert session1 != session2 - session1 = client1.transport.export_data._session - session2 = client2.transport.export_data._session - assert session1 != session2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + assert args[0] == request_msg -def test_parallelstore_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.ParallelstoreGrpcTransport( - host="squid.clam.whelk", - channel=channel, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) -def test_parallelstore_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() - # Check that channel is used if provided. - transport = transports.ParallelstoreGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + assert args[0] == request_msg - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.ParallelstoreGrpcTransport, - transports.ParallelstoreGrpcAsyncIOTransport, - ], -) -def test_parallelstore_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + assert args[0] == request_msg -def test_parallelstore_grpc_lro_client(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_data_empty_call_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_data(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() + assert args[0] == request_msg -def test_parallelstore_grpc_lro_async_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_data_empty_call_grpc_asyncio(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_data(request=None) -def test_address_path(): - project = "squid" - region = "clam" - address = "whelk" - expected = "projects/{project}/regions/{region}/addresses/{address}".format( - project=project, - region=region, - address=address, - ) - actual = ParallelstoreClient.address_path(project, region, address) - assert expected == actual + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() + assert args[0] == request_msg -def test_parse_address_path(): - expected = { - "project": "octopus", - "region": "oyster", - "address": "nudibranch", - } - path = ParallelstoreClient.address_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_address_path(path) - assert expected == actual +def test_transport_kind_rest(): + transport = ParallelstoreClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" -def test_instance_path(): - project = "cuttlefish" - location = "mussel" - instance = "winkle" - expected = "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, +def test_list_instances_rest_bad_request( + request_type=parallelstore.ListInstancesRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.instance_path(project, location, instance) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_instances(request) -def test_parse_instance_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", - } - path = ParallelstoreClient.instance_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_instance_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = ParallelstoreClient( + 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) -def test_network_path(): - project = "squid" - network = "clam" - expected = "projects/{project}/global/networks/{network}".format( - project=project, - network=network, - ) - actual = ParallelstoreClient.network_path(project, network) - assert expected == actual + # 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 = parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_parse_network_path(): - expected = { - "project": "whelk", - "network": "octopus", - } - path = ParallelstoreClient.network_path(**expected) + # Convert return value to protobuf type + return_value = parallelstore.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_instances(request) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_network_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_service_account_path(): - project = "oyster" - service_account = "nudibranch" - expected = "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), ) - actual = ParallelstoreClient.service_account_path(project, service_account) - assert expected == actual + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ListInstancesRequest.pb( + parallelstore.ListInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_parse_service_account_path(): - expected = { - "project": "cuttlefish", - "service_account": "mussel", - } - path = ParallelstoreClient.service_account_path(**expected) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = parallelstore.ListInstancesResponse.to_json( + parallelstore.ListInstancesResponse() + ) + req.return_value.content = return_value - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_service_account_path(path) - assert expected == actual + request = parallelstore.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.ListInstancesResponse() + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = ParallelstoreClient.common_billing_account_path(billing_account) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ParallelstoreClient.common_billing_account_path(**expected) +def test_get_instance_rest_bad_request(request_type=parallelstore.GetInstanceRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_billing_account_path(path) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance(request) -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.common_folder_path(folder) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ParallelstoreClient.common_folder_path(**expected) + # 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 = parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + effective_reserved_ip_range="effective_reserved_ip_range_value", + file_stripe_level=parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN, + directory_stripe_level=parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN, + ) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_folder_path(path) - assert expected == actual + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = parallelstore.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance(request) -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, + # Establish that the response is the type that we expect. + assert isinstance(response, parallelstore.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == parallelstore.Instance.State.CREATING + assert response.capacity_gib == 1247 + assert response.daos_version == "daos_version_value" + assert response.access_points == ["access_points_value"] + assert response.network == "network_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + assert response.effective_reserved_ip_range == "effective_reserved_ip_range_value" + assert ( + response.file_stripe_level + == parallelstore.FileStripeLevel.FILE_STRIPE_LEVEL_MIN + ) + assert ( + response.directory_stripe_level + == parallelstore.DirectoryStripeLevel.DIRECTORY_STRIPE_LEVEL_MIN ) - actual = ParallelstoreClient.common_organization_path(organization) - assert expected == actual - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ParallelstoreClient.common_organization_path(**expected) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_organization_path(path) - assert expected == actual +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.GetInstanceRequest.pb( + parallelstore.GetInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format( - project=project, - ) - actual = ParallelstoreClient.common_project_path(project) - assert expected == actual + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = parallelstore.Instance.to_json(parallelstore.Instance()) + req.return_value.content = return_value + request = parallelstore.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.Instance() -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ParallelstoreClient.common_project_path(**expected) + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_project_path(path) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +def test_create_instance_rest_bad_request( + request_type=parallelstore.CreateInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = ParallelstoreClient.common_location_path(project, location) - assert expected == actual - + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ParallelstoreClient.common_location_path(**expected) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_instance(request) - # Check that the path construction is reversible. - actual = ParallelstoreClient.parse_common_location_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_value", + "effective_reserved_ip_range": "effective_reserved_ip_range_value", + "file_stripe_level": 1, + "directory_stripe_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = parallelstore.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) with mock.patch.object( - transports.ParallelstoreTransport, "_prep_wrapped_messages" - ) as prep: - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.CreateInstanceRequest.pb( + parallelstore.CreateInstanceRequest() ) - prep.assert_called_once_with(client_info) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - with mock.patch.object( - transports.ParallelstoreTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = ParallelstoreClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - prep.assert_called_once_with(client_info) + pre.assert_called_once() + post.assert_called_once() -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + +def test_update_instance_rest_bad_request( + request_type=parallelstore.UpdateInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_value", + "effective_reserved_ip_range": "effective_reserved_ip_range_value", + "file_stripe_level": 1, + "directory_stripe_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = parallelstore.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.UpdateInstanceRequest.pb( + parallelstore.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=parallelstore.DeleteInstanceRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_delete_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.DeleteInstanceRequest.pb( + parallelstore.DeleteInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_data_rest_bad_request(request_type=parallelstore.ImportDataRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ImportDataRequest, + dict, + ], +) +def test_import_data_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_data_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_import_data" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_import_data" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ImportDataRequest.pb( + parallelstore.ImportDataRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.ImportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_data_rest_bad_request(request_type=parallelstore.ExportDataRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ExportDataRequest, + dict, + ], +) +def test_export_data_rest_call_success(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_data_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ParallelstoreRestInterceptor, "post_export_data" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_export_data" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ExportDataRequest.pb( + parallelstore.ExportDataRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = parallelstore.ExportDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_data( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.UpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_data_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_data), "__call__") as call: + client.import_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ImportDataRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_data_empty_call_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_data), "__call__") as call: + client.export_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = parallelstore.ExportDataRequest() + + assert args[0] == request_msg + + +def test_parallelstore_rest_lro_client(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ParallelstoreGrpcTransport, + ) + + +def test_parallelstore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_parallelstore_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_instances", + "get_instance", + "create_instance", + "update_instance", + "delete_instance", + "import_data", + "export_data", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_parallelstore_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.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_parallelstore_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport() + adc.assert_called_once() + + +def test_parallelstore_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParallelstoreClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + transports.ParallelstoreRestTransport, + ], +) +def test_parallelstore_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParallelstoreGrpcTransport, grpc_helpers), + (transports.ParallelstoreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_parallelstore_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "parallelstore.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="parallelstore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_parallelstore_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.ParallelstoreRestTransport( + 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_parallelstore_host_no_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_parallelstore_host_with_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_parallelstore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ParallelstoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ParallelstoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.import_data._session + session2 = client2.transport.import_data._session + assert session1 != session2 + session1 = client1.transport.export_data._session + session2 = client2.transport.export_data._session + assert session1 != session2 + + +def test_parallelstore_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_parallelstore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest -): +def test_parallelstore_grpc_lro_client(): client = ParallelstoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - # 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_location(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.GetLocationRequest, - dict, - ], -) -def test_get_location_rest(request_type): - client = ParallelstoreClient( +def test_parallelstore_grpc_lro_async_client(): + client = ParallelstoreAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc_asyncio", ) - request_init = {"name": "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 = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + transport = client.transport - response = client.get_location(request) + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_address_path(): + project = "squid" + region = "clam" + address = "whelk" + expected = "projects/{project}/regions/{region}/addresses/{address}".format( + project=project, + region=region, + address=address, ) + actual = ParallelstoreClient.address_path(project, region, address) + assert expected == actual - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - - # 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.list_locations(request) +def test_parse_address_path(): + expected = { + "project": "octopus", + "region": "oyster", + "address": "nudibranch", + } + path = ParallelstoreClient.address_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_address_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_instance_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = ParallelstoreClient.instance_path(project, location, instance) + assert expected == actual - response = client.list_locations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) +def test_parse_instance_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "instance": "abalone", + } + path = ParallelstoreClient.instance_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_instance_path(path) + assert expected == actual -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_network_path(): + project = "squid" + network = "clam" + expected = "projects/{project}/global/networks/{network}".format( + project=project, + network=network, ) + actual = ParallelstoreClient.network_path(project, network) + assert expected == actual - # 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.cancel_operation(request) +def test_parse_network_path(): + expected = { + "project": "whelk", + "network": "octopus", + } + path = ParallelstoreClient.network_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_network_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_service_account_path(): + project = "oyster" + service_account = "nudibranch" + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + actual = ParallelstoreClient.service_account_path(project, service_account) + assert expected == actual - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_parse_service_account_path(): + expected = { + "project": "cuttlefish", + "service_account": "mussel", + } + path = ParallelstoreClient.service_account_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_service_account_path(path) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - - # 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.delete_operation(request) + actual = ParallelstoreClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ParallelstoreClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ParallelstoreClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ParallelstoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_folder_path(path) + assert expected == actual -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = ParallelstoreClient.common_organization_path(organization) + assert expected == actual - # 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_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ParallelstoreClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = ParallelstoreClient.common_project_path(project) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ParallelstoreClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_project_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = ParallelstoreClient.common_location_path(project, location) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ParallelstoreClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.list_operations(request) + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ParallelstoreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -7387,7 +7557,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7440,7 +7610,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7485,7 +7655,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -7526,7 +7696,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7579,7 +7749,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7624,7 +7794,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -7665,7 +7835,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7720,7 +7890,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7767,7 +7937,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -7810,7 +7980,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7865,7 +8035,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7912,7 +8082,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -7955,7 +8125,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8010,7 +8180,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8057,7 +8227,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -8100,7 +8270,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8152,7 +8322,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = ParallelstoreAsyncClient(credentials=ga_credentials.AnonymousCredentials()) + client = ParallelstoreAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -8198,7 +8368,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = ParallelstoreAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -8214,22 +8384,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ParallelstoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ParallelstoreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/README.rst b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/README.rst new file mode 100644 index 000000000000..70afea7150f2 --- /dev/null +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PhishingProtectionServiceV1Beta1Transport` is the ABC for all transports. +- public child `PhishingProtectionServiceV1Beta1GrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePhishingProtectionServiceV1Beta1RestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PhishingProtectionServiceV1Beta1RestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/grpc_asyncio.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/grpc_asyncio.py index 097a73af97d5..fde362f6b51f 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/grpc_asyncio.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -280,15 +284,24 @@ def report_phishing( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.report_phishing: gapic_v1.method_async.wrap_method( + self.report_phishing: self._wrap_method( self.report_phishing, default_timeout=600.0, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PhishingProtectionServiceV1Beta1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py index 7d2f56d2bcf6..bab187b99a9e 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.phishingprotection_v1beta1.types import phishingprotection + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePhishingProtectionServiceV1Beta1RestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.phishingprotection_v1beta1.types import phishingprotection - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PhishingProtectionServiceV1Beta1Transport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -109,9 +106,9 @@ class PhishingProtectionServiceV1Beta1RestStub: class PhishingProtectionServiceV1Beta1RestTransport( - PhishingProtectionServiceV1Beta1Transport + _BasePhishingProtectionServiceV1Beta1RestTransport ): - """REST backend transport for PhishingProtectionServiceV1Beta1. + """REST backend synchronous transport for PhishingProtectionServiceV1Beta1. Service to report phishing URIs. @@ -120,7 +117,6 @@ class PhishingProtectionServiceV1Beta1RestTransport( and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -174,21 +170,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -201,19 +188,35 @@ def __init__( ) self._prep_wrapped_messages(client_info) - class _ReportPhishing(PhishingProtectionServiceV1Beta1RestStub): + class _ReportPhishing( + _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing, + PhishingProtectionServiceV1Beta1RestStub, + ): def __hash__(self): - return hash("ReportPhishing") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PhishingProtectionServiceV1Beta1RestTransport.ReportPhishing") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -241,45 +244,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*}/phishing:report", - "body": "*", - }, - ] + http_options = ( + _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing._get_http_options() + ) request, metadata = self._interceptor.pre_report_phishing(request, metadata) - pb_request = phishingprotection.ReportPhishingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PhishingProtectionServiceV1Beta1RestTransport._ReportPhishing._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest_base.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest_base.py new file mode 100644 index 000000000000..40092aa12e68 --- /dev/null +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/services/phishing_protection_service_v1_beta1/transports/rest_base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.phishingprotection_v1beta1.types import phishingprotection + +from .base import DEFAULT_CLIENT_INFO, PhishingProtectionServiceV1Beta1Transport + + +class _BasePhishingProtectionServiceV1Beta1RestTransport( + PhishingProtectionServiceV1Beta1Transport +): + """Base REST backend transport for PhishingProtectionServiceV1Beta1. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "phishingprotection.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'phishingprotection.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseReportPhishing: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*}/phishing:report", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = phishingprotection.ReportPhishingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePhishingProtectionServiceV1Beta1RestTransport._BaseReportPhishing._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePhishingProtectionServiceV1Beta1RestTransport",) diff --git a/packages/google-cloud-phishing-protection/setup.py b/packages/google-cloud-phishing-protection/setup.py index 10ffc1145e1f..152817c4fbb3 100644 --- a/packages/google-cloud-phishing-protection/setup.py +++ b/packages/google-cloud-phishing-protection/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py b/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py index af774419d9f2..823213fa9058 100644 --- a/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py +++ b/packages/google-cloud-phishing-protection/tests/unit/gapic/phishingprotection_v1beta1/test_phishing_protection_service_v1_beta1.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.phishingprotection_v1beta1.services.phishing_protection_service_v1_beta1 import ( PhishingProtectionServiceV1Beta1AsyncClient, PhishingProtectionServiceV1Beta1Client, @@ -51,10 +60,24 @@ from google.cloud.phishingprotection_v1beta1.types import phishingprotection +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1259,25 +1282,6 @@ def test_report_phishing(request_type, transport: str = "grpc"): assert isinstance(response, phishingprotection.ReportPhishingResponse) -def test_report_phishing_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PhishingProtectionServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.report_phishing), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.report_phishing() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == phishingprotection.ReportPhishingRequest() - - def test_report_phishing_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1343,27 +1347,6 @@ def test_report_phishing_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_report_phishing_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.report_phishing), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - phishingprotection.ReportPhishingResponse() - ) - response = await client.report_phishing() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == phishingprotection.ReportPhishingRequest() - - @pytest.mark.asyncio async def test_report_phishing_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1372,7 +1355,7 @@ async def test_report_phishing_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1412,7 +1395,7 @@ async def test_report_phishing_async( request_type=phishingprotection.ReportPhishingRequest, ): client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1475,7 +1458,7 @@ def test_report_phishing_field_headers(): @pytest.mark.asyncio async def test_report_phishing_field_headers_async(): client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1550,7 +1533,7 @@ def test_report_phishing_flattened_error(): @pytest.mark.asyncio async def test_report_phishing_flattened_async(): client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1583,7 +1566,7 @@ async def test_report_phishing_flattened_async(): @pytest.mark.asyncio async def test_report_phishing_flattened_error_async(): client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1596,43 +1579,6 @@ async def test_report_phishing_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - phishingprotection.ReportPhishingRequest, - dict, - ], -) -def test_report_phishing_rest(request_type): - client = PhishingProtectionServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = phishingprotection.ReportPhishingResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = phishingprotection.ReportPhishingResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.report_phishing(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, phishingprotection.ReportPhishingResponse) - - def test_report_phishing_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1765,89 +1711,6 @@ def test_report_phishing_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_report_phishing_rest_interceptors(null_interceptor): - transport = transports.PhishingProtectionServiceV1Beta1RestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PhishingProtectionServiceV1Beta1RestInterceptor(), - ) - client = PhishingProtectionServiceV1Beta1Client(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.PhishingProtectionServiceV1Beta1RestInterceptor, - "post_report_phishing", - ) as post, mock.patch.object( - transports.PhishingProtectionServiceV1Beta1RestInterceptor, - "pre_report_phishing", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = phishingprotection.ReportPhishingRequest.pb( - phishingprotection.ReportPhishingRequest() - ) - 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 = phishingprotection.ReportPhishingResponse.to_json( - phishingprotection.ReportPhishingResponse() - ) - - request = phishingprotection.ReportPhishingRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = phishingprotection.ReportPhishingResponse() - - client.report_phishing( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_report_phishing_rest_bad_request( - transport: str = "rest", request_type=phishingprotection.ReportPhishingRequest -): - client = PhishingProtectionServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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.report_phishing(request) - - def test_report_phishing_rest_flattened(): client = PhishingProtectionServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), @@ -1906,12 +1769,6 @@ def test_report_phishing_rest_flattened_error(transport: str = "rest"): ) -def test_report_phishing_rest_error(): - client = PhishingProtectionServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PhishingProtectionServiceV1Beta1GrpcTransport( @@ -2004,20 +1861,232 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = PhishingProtectionServiceV1Beta1Client.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_phishing_empty_call_grpc(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.report_phishing), "__call__") as call: + call.return_value = phishingprotection.ReportPhishingResponse() + client.report_phishing(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = phishingprotection.ReportPhishingRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PhishingProtectionServiceV1Beta1AsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PhishingProtectionServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_report_phishing_empty_call_grpc_asyncio(): + client = PhishingProtectionServiceV1Beta1AsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.report_phishing), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + phishingprotection.ReportPhishingResponse() + ) + await client.report_phishing(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = phishingprotection.ReportPhishingRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PhishingProtectionServiceV1Beta1Client.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_report_phishing_rest_bad_request( + request_type=phishingprotection.ReportPhishingRequest, +): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.report_phishing(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + phishingprotection.ReportPhishingRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PhishingProtectionServiceV1Beta1Client.get_transport_class( - transport_name - )( +def test_report_phishing_rest_call_success(request_type): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = phishingprotection.ReportPhishingResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = phishingprotection.ReportPhishingResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.report_phishing(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, phishingprotection.ReportPhishingResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_phishing_rest_interceptors(null_interceptor): + transport = transports.PhishingProtectionServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PhishingProtectionServiceV1Beta1RestInterceptor(), + ) + client = PhishingProtectionServiceV1Beta1Client(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.PhishingProtectionServiceV1Beta1RestInterceptor, + "post_report_phishing", + ) as post, mock.patch.object( + transports.PhishingProtectionServiceV1Beta1RestInterceptor, + "pre_report_phishing", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = phishingprotection.ReportPhishingRequest.pb( + phishingprotection.ReportPhishingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = phishingprotection.ReportPhishingResponse.to_json( + phishingprotection.ReportPhishingResponse() + ) + req.return_value.content = return_value + + request = phishingprotection.ReportPhishingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = phishingprotection.ReportPhishingResponse() + + client.report_phishing( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_phishing_empty_call_rest(): + client = PhishingProtectionServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.report_phishing), "__call__") as call: + client.report_phishing(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = phishingprotection.ReportPhishingRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2590,36 +2659,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PhishingProtectionServiceV1Beta1AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PhishingProtectionServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PhishingProtectionServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/README.rst b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/README.rst new file mode 100644 index 000000000000..83ad75711281 --- /dev/null +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`IamCheckerTransport` is the ABC for all transports. +- public child `IamCheckerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `IamCheckerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseIamCheckerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `IamCheckerRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/grpc_asyncio.py b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/grpc_asyncio.py index acc7f9e9791a..3561b9e2026e 100644 --- a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/grpc_asyncio.py +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -275,15 +279,24 @@ def troubleshoot_iam_policy( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.troubleshoot_iam_policy: gapic_v1.method_async.wrap_method( + self.troubleshoot_iam_policy: self._wrap_method( self.troubleshoot_iam_policy, default_timeout=60.0, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("IamCheckerGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest.py b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest.py index f7f5f35145a1..816b5df4a61e 100644 --- a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest.py +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.policytroubleshooter_v1.types import checker + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseIamCheckerRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.policytroubleshooter_v1.types import checker - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import IamCheckerTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -108,8 +105,8 @@ class IamCheckerRestStub: _interceptor: IamCheckerRestInterceptor -class IamCheckerRestTransport(IamCheckerTransport): - """REST backend transport for IamChecker. +class IamCheckerRestTransport(_BaseIamCheckerRestTransport): + """REST backend synchronous transport for IamChecker. IAM Policy Troubleshooter service. @@ -121,7 +118,6 @@ class IamCheckerRestTransport(IamCheckerTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -175,21 +171,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -200,9 +187,34 @@ def __init__( self._interceptor = interceptor or IamCheckerRestInterceptor() self._prep_wrapped_messages(client_info) - class _TroubleshootIamPolicy(IamCheckerRestStub): + class _TroubleshootIamPolicy( + _BaseIamCheckerRestTransport._BaseTroubleshootIamPolicy, IamCheckerRestStub + ): def __hash__(self): - return hash("TroubleshootIamPolicy") + return hash("IamCheckerRestTransport.TroubleshootIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -231,46 +243,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/iam:troubleshoot", - "body": "*", - }, - ] + http_options = ( + _BaseIamCheckerRestTransport._BaseTroubleshootIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_troubleshoot_iam_policy( request, metadata ) - pb_request = checker.TroubleshootIamPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseIamCheckerRestTransport._BaseTroubleshootIamPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseIamCheckerRestTransport._BaseTroubleshootIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseIamCheckerRestTransport._BaseTroubleshootIamPolicy._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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, + response = IamCheckerRestTransport._TroubleshootIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest_base.py b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest_base.py new file mode 100644 index 000000000000..90e5fe8af890 --- /dev/null +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/services/iam_checker/transports/rest_base.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.policytroubleshooter_v1.types import checker + +from .base import DEFAULT_CLIENT_INFO, IamCheckerTransport + + +class _BaseIamCheckerRestTransport(IamCheckerTransport): + """Base REST backend transport for IamChecker. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "policytroubleshooter.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'policytroubleshooter.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseTroubleshootIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/iam:troubleshoot", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checker.TroubleshootIamPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseIamCheckerRestTransport",) diff --git a/packages/google-cloud-policy-troubleshooter/setup.py b/packages/google-cloud-policy-troubleshooter/setup.py index 6606f4f60b24..b8c3631fb94c 100644 --- a/packages/google-cloud-policy-troubleshooter/setup.py +++ b/packages/google-cloud-policy-troubleshooter/setup.py @@ -49,6 +49,7 @@ "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -91,6 +92,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-policy-troubleshooter/tests/unit/gapic/policytroubleshooter_v1/test_iam_checker.py b/packages/google-cloud-policy-troubleshooter/tests/unit/gapic/policytroubleshooter_v1/test_iam_checker.py index aea8ff278a08..1a97ed0832cd 100644 --- a/packages/google-cloud-policy-troubleshooter/tests/unit/gapic/policytroubleshooter_v1/test_iam_checker.py +++ b/packages/google-cloud-policy-troubleshooter/tests/unit/gapic/policytroubleshooter_v1/test_iam_checker.py @@ -22,20 +22,12 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format -from google.rpc import status_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -44,6 +36,23 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.rpc import status_pb2 # type: ignore + from google.cloud.policytroubleshooter_v1.services.iam_checker import ( IamCheckerAsyncClient, IamCheckerClient, @@ -52,10 +61,24 @@ from google.cloud.policytroubleshooter_v1.types import checker, explanations +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1114,27 +1137,6 @@ def test_troubleshoot_iam_policy(request_type, transport: str = "grpc"): assert response.access == explanations.AccessState.GRANTED -def test_troubleshoot_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = IamCheckerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.troubleshoot_iam_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.troubleshoot_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checker.TroubleshootIamPolicyRequest() - - def test_troubleshoot_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1201,31 +1203,6 @@ def test_troubleshoot_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_troubleshoot_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = IamCheckerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.troubleshoot_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - checker.TroubleshootIamPolicyResponse( - access=explanations.AccessState.GRANTED, - ) - ) - response = await client.troubleshoot_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checker.TroubleshootIamPolicyRequest() - - @pytest.mark.asyncio async def test_troubleshoot_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1234,7 +1211,7 @@ async def test_troubleshoot_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = IamCheckerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1273,7 +1250,7 @@ async def test_troubleshoot_iam_policy_async( transport: str = "grpc_asyncio", request_type=checker.TroubleshootIamPolicyRequest ): client = IamCheckerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1309,46 +1286,6 @@ async def test_troubleshoot_iam_policy_async_from_dict(): await test_troubleshoot_iam_policy_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - checker.TroubleshootIamPolicyRequest, - dict, - ], -) -def test_troubleshoot_iam_policy_rest(request_type): - client = IamCheckerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = checker.TroubleshootIamPolicyResponse( - access=explanations.AccessState.GRANTED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = checker.TroubleshootIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.troubleshoot_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, checker.TroubleshootIamPolicyResponse) - assert response.access == explanations.AccessState.GRANTED - - def test_troubleshoot_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1390,93 +1327,6 @@ def test_troubleshoot_iam_policy_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_troubleshoot_iam_policy_rest_interceptors(null_interceptor): - transport = transports.IamCheckerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.IamCheckerRestInterceptor(), - ) - client = IamCheckerClient(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.IamCheckerRestInterceptor, "post_troubleshoot_iam_policy" - ) as post, mock.patch.object( - transports.IamCheckerRestInterceptor, "pre_troubleshoot_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = checker.TroubleshootIamPolicyRequest.pb( - checker.TroubleshootIamPolicyRequest() - ) - 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 = checker.TroubleshootIamPolicyResponse.to_json( - checker.TroubleshootIamPolicyResponse() - ) - - request = checker.TroubleshootIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = checker.TroubleshootIamPolicyResponse() - - client.troubleshoot_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_troubleshoot_iam_policy_rest_bad_request( - transport: str = "rest", request_type=checker.TroubleshootIamPolicyRequest -): - client = IamCheckerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.troubleshoot_iam_policy(request) - - -def test_troubleshoot_iam_policy_rest_error(): - client = IamCheckerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IamCheckerGrpcTransport( @@ -1569,18 +1419,241 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = IamCheckerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_troubleshoot_iam_policy_empty_call_grpc(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + call.return_value = checker.TroubleshootIamPolicyResponse() + client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checker.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = IamCheckerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = IamCheckerAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_troubleshoot_iam_policy_empty_call_grpc_asyncio(): + client = IamCheckerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checker.TroubleshootIamPolicyResponse( + access=explanations.AccessState.GRANTED, + ) + ) + await client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checker.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = IamCheckerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_troubleshoot_iam_policy_rest_bad_request( + request_type=checker.TroubleshootIamPolicyRequest, +): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.troubleshoot_iam_policy(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + checker.TroubleshootIamPolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = IamCheckerClient.get_transport_class(transport_name)( +def test_troubleshoot_iam_policy_rest_call_success(request_type): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = checker.TroubleshootIamPolicyResponse( + access=explanations.AccessState.GRANTED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = checker.TroubleshootIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.troubleshoot_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checker.TroubleshootIamPolicyResponse) + assert response.access == explanations.AccessState.GRANTED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_troubleshoot_iam_policy_rest_interceptors(null_interceptor): + transport = transports.IamCheckerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.IamCheckerRestInterceptor(), ) - assert transport.kind == transport_name + client = IamCheckerClient(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.IamCheckerRestInterceptor, "post_troubleshoot_iam_policy" + ) as post, mock.patch.object( + transports.IamCheckerRestInterceptor, "pre_troubleshoot_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = checker.TroubleshootIamPolicyRequest.pb( + checker.TroubleshootIamPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = checker.TroubleshootIamPolicyResponse.to_json( + checker.TroubleshootIamPolicyResponse() + ) + req.return_value.content = return_value + + request = checker.TroubleshootIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checker.TroubleshootIamPolicyResponse() + + client.troubleshoot_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_troubleshoot_iam_policy_empty_call_rest(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checker.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2119,36 +2192,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = IamCheckerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = IamCheckerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = IamCheckerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/async_client.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/async_client.py index 1b3e1684ea1b..55c1eefd489a 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/async_client.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/async_client.py @@ -680,11 +680,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -737,11 +733,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/client.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/client.py index 1394da8ef751..8809c064b45d 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/client.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/client.py @@ -1130,11 +1130,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1187,11 +1183,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/README.rst b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/README.rst new file mode 100644 index 000000000000..5f1ac9d029fb --- /dev/null +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SimulatorTransport` is the ABC for all transports. +- public child `SimulatorGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SimulatorGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSimulatorRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SimulatorRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/base.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/base.py index 7994ca3c0d15..6833949ed49e 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/base.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/base.py @@ -162,6 +162,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/grpc_asyncio.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/grpc_asyncio.py index d0241fb22ceb..4bda0d77dc28 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/grpc_asyncio.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -240,6 +241,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -357,7 +361,7 @@ def list_replay_results( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_replay: gapic_v1.method_async.wrap_method( + self.get_replay: self._wrap_method( self.get_replay, default_retry=retries.AsyncRetry( initial=1.0, @@ -371,12 +375,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.create_replay: gapic_v1.method_async.wrap_method( + self.create_replay: self._wrap_method( self.create_replay, default_timeout=60.0, client_info=client_info, ), - self.list_replay_results: gapic_v1.method_async.wrap_method( + self.list_replay_results: self._wrap_method( self.list_replay_results, default_retry=retries.AsyncRetry( initial=1.0, @@ -390,11 +394,30 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest.py index a8911f390df1..d4f3880612c3 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest.py @@ -16,39 +16,29 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.policysimulator_v1.types import simulator + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSimulatorRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.policysimulator_v1.types import simulator - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import SimulatorTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -220,8 +210,8 @@ class SimulatorRestStub: _interceptor: SimulatorRestInterceptor -class SimulatorRestTransport(SimulatorTransport): - """REST backend transport for Simulator. +class SimulatorRestTransport(_BaseSimulatorRestTransport): + """REST backend synchronous transport for Simulator. Policy Simulator API service. @@ -242,7 +232,6 @@ class SimulatorRestTransport(SimulatorTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -296,21 +285,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -386,19 +366,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateReplay(SimulatorRestStub): + class _CreateReplay( + _BaseSimulatorRestTransport._BaseCreateReplay, SimulatorRestStub + ): def __hash__(self): - return hash("CreateReplay") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SimulatorRestTransport.CreateReplay") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -428,55 +423,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/replays", - "body": "replay", - }, - { - "method": "post", - "uri": "/v1/{parent=folders/*/locations/*}/replays", - "body": "replay", - }, - { - "method": "post", - "uri": "/v1/{parent=organizations/*/locations/*}/replays", - "body": "replay", - }, - ] + http_options = ( + _BaseSimulatorRestTransport._BaseCreateReplay._get_http_options() + ) request, metadata = self._interceptor.pre_create_replay(request, metadata) - pb_request = simulator.CreateReplayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseSimulatorRestTransport._BaseCreateReplay._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseSimulatorRestTransport._BaseCreateReplay._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseSimulatorRestTransport._BaseCreateReplay._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = SimulatorRestTransport._CreateReplay._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -490,19 +466,31 @@ def __call__( resp = self._interceptor.post_create_replay(resp) return resp - class _GetReplay(SimulatorRestStub): + class _GetReplay(_BaseSimulatorRestTransport._BaseGetReplay, SimulatorRestStub): def __hash__(self): - return hash("GetReplay") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SimulatorRestTransport.GetReplay") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -529,46 +517,31 @@ def __call__( A resource describing a ``Replay``, or simulation. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/replays/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/replays/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/replays/*}", - }, - ] + http_options = ( + _BaseSimulatorRestTransport._BaseGetReplay._get_http_options() + ) request, metadata = self._interceptor.pre_get_replay(request, metadata) - pb_request = simulator.GetReplayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseSimulatorRestTransport._BaseGetReplay._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseSimulatorRestTransport._BaseGetReplay._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = SimulatorRestTransport._GetReplay._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -584,19 +557,33 @@ def __call__( resp = self._interceptor.post_get_replay(resp) return resp - class _ListReplayResults(SimulatorRestStub): + class _ListReplayResults( + _BaseSimulatorRestTransport._BaseListReplayResults, SimulatorRestStub + ): def __hash__(self): - return hash("ListReplayResults") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SimulatorRestTransport.ListReplayResults") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -625,48 +612,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/replays/*}/results", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*/replays/*}/results", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*/replays/*}/results", - }, - ] + http_options = ( + _BaseSimulatorRestTransport._BaseListReplayResults._get_http_options() + ) request, metadata = self._interceptor.pre_list_replay_results( request, metadata ) - pb_request = simulator.ListReplayResultsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSimulatorRestTransport._BaseListReplayResults._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseSimulatorRestTransport._BaseListReplayResults._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = SimulatorRestTransport._ListReplayResults._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -710,7 +678,34 @@ def list_replay_results( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(SimulatorRestStub): + class _GetOperation( + _BaseSimulatorRestTransport._BaseGetOperation, SimulatorRestStub + ): + def __hash__(self): + return hash("SimulatorRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -734,44 +729,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=operations/**}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/replays/*/operations/**}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/replays/*/operations/**}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/replays/*/operations/**}", - }, - ] - + http_options = ( + _BaseSimulatorRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseSimulatorRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseSimulatorRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = SimulatorRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -779,8 +761,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -788,7 +771,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(SimulatorRestStub): + class _ListOperations( + _BaseSimulatorRestTransport._BaseListOperations, SimulatorRestStub + ): + def __hash__(self): + return hash("SimulatorRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -812,44 +822,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=operations}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/replays/*/operations}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/replays/*/operations}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/replays/*/operations}", - }, - ] - + http_options = ( + _BaseSimulatorRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseSimulatorRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseSimulatorRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = SimulatorRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -857,8 +854,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest_base.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest_base.py new file mode 100644 index 000000000000..ee5a7cdd2056 --- /dev/null +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/services/simulator/transports/rest_base.py @@ -0,0 +1,343 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.policysimulator_v1.types import simulator + +from .base import DEFAULT_CLIENT_INFO, SimulatorTransport + + +class _BaseSimulatorRestTransport(SimulatorTransport): + """Base REST backend transport for Simulator. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "policysimulator.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'policysimulator.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateReplay: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/replays", + "body": "replay", + }, + { + "method": "post", + "uri": "/v1/{parent=folders/*/locations/*}/replays", + "body": "replay", + }, + { + "method": "post", + "uri": "/v1/{parent=organizations/*/locations/*}/replays", + "body": "replay", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = simulator.CreateReplayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSimulatorRestTransport._BaseCreateReplay._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetReplay: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/replays/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/replays/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/replays/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = simulator.GetReplayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSimulatorRestTransport._BaseGetReplay._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListReplayResults: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/replays/*}/results", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*/replays/*}/results", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/replays/*}/results", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = simulator.ListReplayResultsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSimulatorRestTransport._BaseListReplayResults._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=operations/**}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/replays/*/operations/**}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/replays/*/operations/**}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/replays/*/operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=operations}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/replays/*/operations}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/replays/*/operations}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/replays/*/operations}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSimulatorRestTransport",) diff --git a/packages/google-cloud-policysimulator/setup.py b/packages/google-cloud-policysimulator/setup.py index d3bc5eb70f95..56fc78aacf98 100644 --- a/packages/google-cloud-policysimulator/setup.py +++ b/packages/google-cloud-policysimulator/setup.py @@ -49,6 +49,7 @@ "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -91,6 +92,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-policysimulator/tests/unit/gapic/policysimulator_v1/test_simulator.py b/packages/google-cloud-policysimulator/tests/unit/gapic/policysimulator_v1/test_simulator.py index ebb56653ef15..b77de10b2adc 100644 --- a/packages/google-cloud-policysimulator/tests/unit/gapic/policysimulator_v1/test_simulator.py +++ b/packages/google-cloud-policysimulator/tests/unit/gapic/policysimulator_v1/test_simulator.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,16 +62,8 @@ from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.type import date_pb2 # type: ignore from google.type import expr_pb2 # type: ignore -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.policysimulator_v1.services.simulator import ( SimulatorAsyncClient, @@ -65,10 +74,24 @@ from google.cloud.policysimulator_v1.types import simulator +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1123,25 +1146,6 @@ def test_get_replay(request_type, transport: str = "grpc"): assert response.state == simulator.Replay.State.PENDING -def test_get_replay_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_replay), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_replay() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.GetReplayRequest() - - def test_get_replay_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1205,37 +1209,13 @@ def test_get_replay_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_replay_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_replay), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - simulator.Replay( - name="name_value", - state=simulator.Replay.State.PENDING, - ) - ) - response = await client.get_replay() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.GetReplayRequest() - - @pytest.mark.asyncio async def test_get_replay_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1274,7 +1254,7 @@ async def test_get_replay_async( transport: str = "grpc_asyncio", request_type=simulator.GetReplayRequest ): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1342,7 +1322,7 @@ def test_get_replay_field_headers(): @pytest.mark.asyncio async def test_get_replay_field_headers_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1410,7 +1390,7 @@ def test_get_replay_flattened_error(): @pytest.mark.asyncio async def test_get_replay_flattened_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1437,7 +1417,7 @@ async def test_get_replay_flattened_async(): @pytest.mark.asyncio async def test_get_replay_flattened_error_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1482,25 +1462,6 @@ def test_create_replay(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_replay_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_replay), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_replay() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.CreateReplayRequest() - - def test_create_replay_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1569,27 +1530,6 @@ def test_create_replay_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_replay_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_replay), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_replay() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.CreateReplayRequest() - - @pytest.mark.asyncio async def test_create_replay_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1598,7 +1538,7 @@ async def test_create_replay_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1642,7 +1582,7 @@ async def test_create_replay_async( transport: str = "grpc_asyncio", request_type=simulator.CreateReplayRequest ): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1705,7 +1645,7 @@ def test_create_replay_field_headers(): @pytest.mark.asyncio async def test_create_replay_field_headers_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1780,7 +1720,7 @@ def test_create_replay_flattened_error(): @pytest.mark.asyncio async def test_create_replay_flattened_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1813,7 +1753,7 @@ async def test_create_replay_flattened_async(): @pytest.mark.asyncio async def test_create_replay_flattened_error_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1864,27 +1804,6 @@ def test_list_replay_results(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_replay_results_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_replay_results), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_replay_results() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.ListReplayResultsRequest() - - def test_list_replay_results_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1956,31 +1875,6 @@ def test_list_replay_results_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_replay_results_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_replay_results), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - simulator.ListReplayResultsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_replay_results() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == simulator.ListReplayResultsRequest() - - @pytest.mark.asyncio async def test_list_replay_results_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1989,7 +1883,7 @@ async def test_list_replay_results_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2028,7 +1922,7 @@ async def test_list_replay_results_async( transport: str = "grpc_asyncio", request_type=simulator.ListReplayResultsRequest ): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2098,7 +1992,7 @@ def test_list_replay_results_field_headers(): @pytest.mark.asyncio async def test_list_replay_results_field_headers_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2172,7 +2066,7 @@ def test_list_replay_results_flattened_error(): @pytest.mark.asyncio async def test_list_replay_results_flattened_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2203,7 +2097,7 @@ async def test_list_replay_results_flattened_async(): @pytest.mark.asyncio async def test_list_replay_results_flattened_error_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2317,7 +2211,7 @@ def test_list_replay_results_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_replay_results_async_pager(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2369,7 +2263,7 @@ async def test_list_replay_results_async_pager(): @pytest.mark.asyncio async def test_list_replay_results_async_pages(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2417,48 +2311,6 @@ async def test_list_replay_results_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - simulator.GetReplayRequest, - dict, - ], -) -def test_get_replay_rest(request_type): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/replays/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 = simulator.Replay( - name="name_value", - state=simulator.Replay.State.PENDING, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulator.Replay.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_replay(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, simulator.Replay) - assert response.name == "name_value" - assert response.state == simulator.Replay.State.PENDING - - def test_get_replay_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2576,81 +2428,6 @@ def test_get_replay_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_replay_rest_interceptors(null_interceptor): - transport = transports.SimulatorRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), - ) - client = SimulatorClient(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.SimulatorRestInterceptor, "post_get_replay" - ) as post, mock.patch.object( - transports.SimulatorRestInterceptor, "pre_get_replay" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = simulator.GetReplayRequest.pb(simulator.GetReplayRequest()) - 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 = simulator.Replay.to_json(simulator.Replay()) - - request = simulator.GetReplayRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulator.Replay() - - client.get_replay( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_replay_rest_bad_request( - transport: str = "rest", request_type=simulator.GetReplayRequest -): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/replays/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.get_replay(request) - - def test_get_replay_rest_flattened(): client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2707,127 +2484,6 @@ def test_get_replay_rest_flattened_error(transport: str = "rest"): ) -def test_get_replay_rest_error(): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - simulator.CreateReplayRequest, - dict, - ], -) -def test_create_replay_rest(request_type): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["replay"] = { - "name": "name_value", - "state": 1, - "config": {"policy_overlay": {}, "log_source": 1}, - "results_summary": { - "log_count": 970, - "unchanged_count": 1589, - "difference_count": 1683, - "error_count": 1202, - "oldest_date": {"year": 433, "month": 550, "day": 318}, - "newest_date": {}, - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = simulator.CreateReplayRequest.meta.fields["replay"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["replay"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["replay"][field])): - del request_init["replay"][field][i][subfield] - else: - del request_init["replay"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_replay(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_replay_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2955,85 +2611,6 @@ def test_create_replay_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_replay_rest_interceptors(null_interceptor): - transport = transports.SimulatorRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), - ) - client = SimulatorClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.SimulatorRestInterceptor, "post_create_replay" - ) as post, mock.patch.object( - transports.SimulatorRestInterceptor, "pre_create_replay" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = simulator.CreateReplayRequest.pb(simulator.CreateReplayRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = simulator.CreateReplayRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_replay( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_replay_rest_bad_request( - transport: str = "rest", request_type=simulator.CreateReplayRequest -): - client = SimulatorClient( - 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.create_replay(request) - - def test_create_replay_rest_flattened(): client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3090,52 +2667,6 @@ def test_create_replay_rest_flattened_error(transport: str = "rest"): ) -def test_create_replay_rest_error(): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - simulator.ListReplayResultsRequest, - dict, - ], -) -def test_list_replay_results_rest(request_type): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/replays/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 = simulator.ListReplayResultsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = simulator.ListReplayResultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_replay_results(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReplayResultsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_replay_results_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3274,89 +2805,10 @@ def test_list_replay_results_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_replay_results_rest_interceptors(null_interceptor): - transport = transports.SimulatorRestTransport( +def test_list_replay_results_rest_flattened(): + client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), - ) - client = SimulatorClient(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.SimulatorRestInterceptor, "post_list_replay_results" - ) as post, mock.patch.object( - transports.SimulatorRestInterceptor, "pre_list_replay_results" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = simulator.ListReplayResultsRequest.pb( - simulator.ListReplayResultsRequest() - ) - 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 = simulator.ListReplayResultsResponse.to_json( - simulator.ListReplayResultsResponse() - ) - - request = simulator.ListReplayResultsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = simulator.ListReplayResultsResponse() - - client.list_replay_results( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_replay_results_rest_bad_request( - transport: str = "rest", request_type=simulator.ListReplayResultsRequest -): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/replays/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.list_replay_results(request) - - -def test_list_replay_results_rest_flattened(): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -3518,69 +2970,862 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.SimulatorGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # It is an error to provide scopes and a transport instance. + transport = transports.SimulatorGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SimulatorClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SimulatorGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SimulatorClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SimulatorGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SimulatorGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SimulatorGrpcTransport, + transports.SimulatorGrpcAsyncIOTransport, + transports.SimulatorRestTransport, + ], +) +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_transport_kind_grpc(): + transport = SimulatorClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_replay_empty_call_grpc(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_replay), "__call__") as call: + call.return_value = simulator.Replay() + client.get_replay(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.GetReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_replay_empty_call_grpc(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_replay), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_replay(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.CreateReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_replay_results_empty_call_grpc(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_replay_results), "__call__" + ) as call: + call.return_value = simulator.ListReplayResultsResponse() + client.list_replay_results(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.ListReplayResultsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SimulatorAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SimulatorAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_replay_empty_call_grpc_asyncio(): + client = SimulatorAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_replay), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + simulator.Replay( + name="name_value", + state=simulator.Replay.State.PENDING, + ) + ) + await client.get_replay(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.GetReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_replay_empty_call_grpc_asyncio(): + client = SimulatorAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_replay), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_replay(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.CreateReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_replay_results_empty_call_grpc_asyncio(): + client = SimulatorAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_replay_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + simulator.ListReplayResultsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_replay_results(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.ListReplayResultsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SimulatorClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_replay_rest_bad_request(request_type=simulator.GetReplayRequest): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/replays/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_replay(request) + + +@pytest.mark.parametrize( + "request_type", + [ + simulator.GetReplayRequest, + dict, + ], +) +def test_get_replay_rest_call_success(request_type): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/replays/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 = simulator.Replay( + name="name_value", + state=simulator.Replay.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulator.Replay.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_replay(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulator.Replay) + assert response.name == "name_value" + assert response.state == simulator.Replay.State.PENDING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_replay_rest_interceptors(null_interceptor): + transport = transports.SimulatorRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), + ) + client = SimulatorClient(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.SimulatorRestInterceptor, "post_get_replay" + ) as post, mock.patch.object( + transports.SimulatorRestInterceptor, "pre_get_replay" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = simulator.GetReplayRequest.pb(simulator.GetReplayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = simulator.Replay.to_json(simulator.Replay()) + req.return_value.content = return_value + + request = simulator.GetReplayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulator.Replay() + + client.get_replay( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_replay_rest_bad_request(request_type=simulator.CreateReplayRequest): + client = SimulatorClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_replay(request) + + +@pytest.mark.parametrize( + "request_type", + [ + simulator.CreateReplayRequest, + dict, + ], +) +def test_create_replay_rest_call_success(request_type): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["replay"] = { + "name": "name_value", + "state": 1, + "config": {"policy_overlay": {}, "log_source": 1}, + "results_summary": { + "log_count": 970, + "unchanged_count": 1589, + "difference_count": 1683, + "error_count": 1202, + "oldest_date": {"year": 433, "month": 550, "day": 318}, + "newest_date": {}, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = simulator.CreateReplayRequest.meta.fields["replay"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["replay"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["replay"][field])): + del request_init["replay"][field][i][subfield] + else: + del request_init["replay"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_replay(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_replay_rest_interceptors(null_interceptor): + transport = transports.SimulatorRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), + ) + client = SimulatorClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SimulatorRestInterceptor, "post_create_replay" + ) as post, mock.patch.object( + transports.SimulatorRestInterceptor, "pre_create_replay" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = simulator.CreateReplayRequest.pb(simulator.CreateReplayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = simulator.CreateReplayRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_replay( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_replay_results_rest_bad_request( + request_type=simulator.ListReplayResultsRequest, +): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/replays/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_replay_results(request) + + +@pytest.mark.parametrize( + "request_type", + [ + simulator.ListReplayResultsRequest, + dict, + ], +) +def test_list_replay_results_rest_call_success(request_type): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/replays/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 = simulator.ListReplayResultsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = simulator.ListReplayResultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_replay_results(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReplayResultsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_replay_results_rest_interceptors(null_interceptor): + transport = transports.SimulatorRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SimulatorRestInterceptor(), + ) + client = SimulatorClient(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.SimulatorRestInterceptor, "post_list_replay_results" + ) as post, mock.patch.object( + transports.SimulatorRestInterceptor, "pre_list_replay_results" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = simulator.ListReplayResultsRequest.pb( + simulator.ListReplayResultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = simulator.ListReplayResultsResponse.to_json( + simulator.ListReplayResultsResponse() + ) + req.return_value.content = return_value + + request = simulator.ListReplayResultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulator.ListReplayResultsResponse() + + client.list_replay_results( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = SimulatorClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + assert client is not None -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SimulatorGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_replay_empty_call_rest(): + client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = SimulatorClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_replay), "__call__") as call: + client.get_replay(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SimulatorGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.GetReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_replay_empty_call_rest(): + client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.SimulatorGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_replay), "__call__") as call: + client.create_replay(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.CreateReplayRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_replay_results_empty_call_rest(): + client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_replay_results), "__call__" + ) as call: + client.list_replay_results(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.SimulatorGrpcTransport, - transports.SimulatorGrpcAsyncIOTransport, - transports.SimulatorRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = simulator.ListReplayResultsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = SimulatorClient.get_transport_class(transport_name)( + +def test_simulator_rest_lro_client(): + client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -3818,23 +4063,6 @@ def test_simulator_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_simulator_rest_lro_client(): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -4244,132 +4472,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations"}, request) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations"} - 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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = SimulatorClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4397,7 +4499,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4452,7 +4554,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4499,7 +4601,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -4542,7 +4644,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4597,7 +4699,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4644,7 +4746,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = SimulatorAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -4660,22 +4762,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = SimulatorClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SimulatorAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SimulatorClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/README.rst b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/README.rst new file mode 100644 index 000000000000..1953bf541f2d --- /dev/null +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PolicyTroubleshooterTransport` is the ABC for all transports. +- public child `PolicyTroubleshooterGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PolicyTroubleshooterGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePolicyTroubleshooterRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PolicyTroubleshooterRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/grpc_asyncio.py b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/grpc_asyncio.py index 4705939f2cca..c489df56b809 100644 --- a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/grpc_asyncio.py +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -275,7 +279,7 @@ def troubleshoot_iam_policy( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.troubleshoot_iam_policy: gapic_v1.method_async.wrap_method( + self.troubleshoot_iam_policy: self._wrap_method( self.troubleshoot_iam_policy, default_retry=retries.AsyncRetry( initial=1.0, @@ -291,8 +295,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PolicyTroubleshooterGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest.py b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest.py index 0be0187a9c5d..d80df79ecc31 100644 --- a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest.py +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.policytroubleshooter_iam_v3.types import troubleshooter + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePolicyTroubleshooterRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.policytroubleshooter_iam_v3.types import troubleshooter - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PolicyTroubleshooterTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -108,8 +105,8 @@ class PolicyTroubleshooterRestStub: _interceptor: PolicyTroubleshooterRestInterceptor -class PolicyTroubleshooterRestTransport(PolicyTroubleshooterTransport): - """REST backend transport for PolicyTroubleshooter. +class PolicyTroubleshooterRestTransport(_BasePolicyTroubleshooterRestTransport): + """REST backend synchronous transport for PolicyTroubleshooter. IAM Policy Troubleshooter service. @@ -121,7 +118,6 @@ class PolicyTroubleshooterRestTransport(PolicyTroubleshooterTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -175,21 +171,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -200,9 +187,35 @@ def __init__( self._interceptor = interceptor or PolicyTroubleshooterRestInterceptor() self._prep_wrapped_messages(client_info) - class _TroubleshootIamPolicy(PolicyTroubleshooterRestStub): + class _TroubleshootIamPolicy( + _BasePolicyTroubleshooterRestTransport._BaseTroubleshootIamPolicy, + PolicyTroubleshooterRestStub, + ): def __hash__(self): - return hash("TroubleshootIamPolicy") + return hash("PolicyTroubleshooterRestTransport.TroubleshootIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -231,46 +244,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/iam:troubleshoot", - "body": "*", - }, - ] + http_options = ( + _BasePolicyTroubleshooterRestTransport._BaseTroubleshootIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_troubleshoot_iam_policy( request, metadata ) - pb_request = troubleshooter.TroubleshootIamPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePolicyTroubleshooterRestTransport._BaseTroubleshootIamPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePolicyTroubleshooterRestTransport._BaseTroubleshootIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePolicyTroubleshooterRestTransport._BaseTroubleshootIamPolicy._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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, + response = ( + PolicyTroubleshooterRestTransport._TroubleshootIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest_base.py b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest_base.py new file mode 100644 index 000000000000..a6e33390aa0d --- /dev/null +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/services/policy_troubleshooter/transports/rest_base.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.policytroubleshooter_iam_v3.types import troubleshooter + +from .base import DEFAULT_CLIENT_INFO, PolicyTroubleshooterTransport + + +class _BasePolicyTroubleshooterRestTransport(PolicyTroubleshooterTransport): + """Base REST backend transport for PolicyTroubleshooter. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "policytroubleshooter.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'policytroubleshooter.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseTroubleshootIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/iam:troubleshoot", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = troubleshooter.TroubleshootIamPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePolicyTroubleshooterRestTransport",) diff --git a/packages/google-cloud-policytroubleshooter-iam/setup.py b/packages/google-cloud-policytroubleshooter-iam/setup.py index c75da84e2152..7d17e245cdaf 100644 --- a/packages/google-cloud-policytroubleshooter-iam/setup.py +++ b/packages/google-cloud-policytroubleshooter-iam/setup.py @@ -50,6 +50,7 @@ "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", "google-cloud-iam >= 2.12.2, <3.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -92,6 +93,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-policytroubleshooter-iam/tests/unit/gapic/policytroubleshooter_iam_v3/test_policy_troubleshooter.py b/packages/google-cloud-policytroubleshooter-iam/tests/unit/gapic/policytroubleshooter_iam_v3/test_policy_troubleshooter.py index 2424e60929e8..f05f61c1315d 100644 --- a/packages/google-cloud-policytroubleshooter-iam/tests/unit/gapic/policytroubleshooter_iam_v3/test_policy_troubleshooter.py +++ b/packages/google-cloud-policytroubleshooter-iam/tests/unit/gapic/policytroubleshooter_iam_v3/test_policy_troubleshooter.py @@ -22,20 +22,12 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format -from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -44,6 +36,23 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore + from google.cloud.policytroubleshooter_iam_v3.services.policy_troubleshooter import ( PolicyTroubleshooterAsyncClient, PolicyTroubleshooterClient, @@ -52,10 +61,24 @@ from google.cloud.policytroubleshooter_iam_v3.types import troubleshooter +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1226,27 +1249,6 @@ def test_troubleshoot_iam_policy(request_type, transport: str = "grpc"): ) -def test_troubleshoot_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTroubleshooterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.troubleshoot_iam_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.troubleshoot_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == troubleshooter.TroubleshootIamPolicyRequest() - - def test_troubleshoot_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1313,31 +1315,6 @@ def test_troubleshoot_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_troubleshoot_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PolicyTroubleshooterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.troubleshoot_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - troubleshooter.TroubleshootIamPolicyResponse( - overall_access_state=troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS, - ) - ) - response = await client.troubleshoot_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == troubleshooter.TroubleshootIamPolicyRequest() - - @pytest.mark.asyncio async def test_troubleshoot_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1346,7 +1323,7 @@ async def test_troubleshoot_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PolicyTroubleshooterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1386,7 +1363,7 @@ async def test_troubleshoot_iam_policy_async( request_type=troubleshooter.TroubleshootIamPolicyRequest, ): client = PolicyTroubleshooterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1425,49 +1402,6 @@ async def test_troubleshoot_iam_policy_async_from_dict(): await test_troubleshoot_iam_policy_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - troubleshooter.TroubleshootIamPolicyRequest, - dict, - ], -) -def test_troubleshoot_iam_policy_rest(request_type): - client = PolicyTroubleshooterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = troubleshooter.TroubleshootIamPolicyResponse( - overall_access_state=troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = troubleshooter.TroubleshootIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.troubleshoot_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, troubleshooter.TroubleshootIamPolicyResponse) - assert ( - response.overall_access_state - == troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS - ) - - def test_troubleshoot_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1509,95 +1443,6 @@ def test_troubleshoot_iam_policy_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_troubleshoot_iam_policy_rest_interceptors(null_interceptor): - transport = transports.PolicyTroubleshooterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PolicyTroubleshooterRestInterceptor(), - ) - client = PolicyTroubleshooterClient(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.PolicyTroubleshooterRestInterceptor, "post_troubleshoot_iam_policy" - ) as post, mock.patch.object( - transports.PolicyTroubleshooterRestInterceptor, "pre_troubleshoot_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = troubleshooter.TroubleshootIamPolicyRequest.pb( - troubleshooter.TroubleshootIamPolicyRequest() - ) - 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 = ( - troubleshooter.TroubleshootIamPolicyResponse.to_json( - troubleshooter.TroubleshootIamPolicyResponse() - ) - ) - - request = troubleshooter.TroubleshootIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = troubleshooter.TroubleshootIamPolicyResponse() - - client.troubleshoot_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_troubleshoot_iam_policy_rest_bad_request( - transport: str = "rest", request_type=troubleshooter.TroubleshootIamPolicyRequest -): - client = PolicyTroubleshooterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.troubleshoot_iam_policy(request) - - -def test_troubleshoot_iam_policy_rest_error(): - client = PolicyTroubleshooterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PolicyTroubleshooterGrpcTransport( @@ -1690,18 +1535,244 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = PolicyTroubleshooterClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_troubleshoot_iam_policy_empty_call_grpc(): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + call.return_value = troubleshooter.TroubleshootIamPolicyResponse() + client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = troubleshooter.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PolicyTroubleshooterAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PolicyTroubleshooterAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_troubleshoot_iam_policy_empty_call_grpc_asyncio(): + client = PolicyTroubleshooterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + troubleshooter.TroubleshootIamPolicyResponse( + overall_access_state=troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS, + ) + ) + await client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = troubleshooter.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PolicyTroubleshooterClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_troubleshoot_iam_policy_rest_bad_request( + request_type=troubleshooter.TroubleshootIamPolicyRequest, +): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.troubleshoot_iam_policy(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + troubleshooter.TroubleshootIamPolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PolicyTroubleshooterClient.get_transport_class(transport_name)( +def test_troubleshoot_iam_policy_rest_call_success(request_type): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = troubleshooter.TroubleshootIamPolicyResponse( + overall_access_state=troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = troubleshooter.TroubleshootIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.troubleshoot_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, troubleshooter.TroubleshootIamPolicyResponse) + assert ( + response.overall_access_state + == troubleshooter.TroubleshootIamPolicyResponse.OverallAccessState.CAN_ACCESS + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_troubleshoot_iam_policy_rest_interceptors(null_interceptor): + transport = transports.PolicyTroubleshooterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PolicyTroubleshooterRestInterceptor(), + ) + client = PolicyTroubleshooterClient(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.PolicyTroubleshooterRestInterceptor, "post_troubleshoot_iam_policy" + ) as post, mock.patch.object( + transports.PolicyTroubleshooterRestInterceptor, "pre_troubleshoot_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = troubleshooter.TroubleshootIamPolicyRequest.pb( + troubleshooter.TroubleshootIamPolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = troubleshooter.TroubleshootIamPolicyResponse.to_json( + troubleshooter.TroubleshootIamPolicyResponse() + ) + req.return_value.content = return_value + + request = troubleshooter.TroubleshootIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = troubleshooter.TroubleshootIamPolicyResponse() + + client.troubleshoot_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_troubleshoot_iam_policy_empty_call_rest(): + client = PolicyTroubleshooterClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.troubleshoot_iam_policy), "__call__" + ) as call: + client.troubleshoot_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = troubleshooter.TroubleshootIamPolicyRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2253,36 +2324,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PolicyTroubleshooterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PolicyTroubleshooterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PolicyTroubleshooterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py index 1f75bf37a0ab..46e642f28c84 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py @@ -4091,11 +4091,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -4148,11 +4144,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4209,11 +4201,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4266,11 +4254,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4386,11 +4370,7 @@ async def set_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -4510,11 +4490,7 @@ async def get_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -4572,11 +4548,9 @@ async def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] # Certain fields should be provided within the metadata header; # add these here. @@ -4629,11 +4603,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -4686,11 +4656,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py index c3d6c8d07687..faea6ad6f67a 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py @@ -4549,11 +4549,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -4606,11 +4602,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4667,11 +4659,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4724,11 +4712,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -4844,11 +4828,7 @@ def set_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -4968,11 +4948,7 @@ def get_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -5030,11 +5006,7 @@ def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Certain fields should be provided within the metadata header; # add these here. @@ -5087,11 +5059,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -5144,11 +5112,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/README.rst b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/README.rst new file mode 100644 index 000000000000..7e9a06b69852 --- /dev/null +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CertificateAuthorityServiceTransport` is the ABC for all transports. +- public child `CertificateAuthorityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CertificateAuthorityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCertificateAuthorityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CertificateAuthorityServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py index 8952efa43c53..7b4d66bf8380 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py @@ -277,6 +277,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py index 758b1b1c8878..4cc625ede062 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -235,6 +236,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -1140,156 +1144,210 @@ def update_certificate_template( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_certificate: gapic_v1.method_async.wrap_method( + self.create_certificate: self._wrap_method( self.create_certificate, default_timeout=None, client_info=client_info, ), - self.get_certificate: gapic_v1.method_async.wrap_method( + self.get_certificate: self._wrap_method( self.get_certificate, default_timeout=None, client_info=client_info, ), - self.list_certificates: gapic_v1.method_async.wrap_method( + self.list_certificates: self._wrap_method( self.list_certificates, default_timeout=None, client_info=client_info, ), - self.revoke_certificate: gapic_v1.method_async.wrap_method( + self.revoke_certificate: self._wrap_method( self.revoke_certificate, default_timeout=None, client_info=client_info, ), - self.update_certificate: gapic_v1.method_async.wrap_method( + self.update_certificate: self._wrap_method( self.update_certificate, default_timeout=None, client_info=client_info, ), - self.activate_certificate_authority: gapic_v1.method_async.wrap_method( + self.activate_certificate_authority: self._wrap_method( self.activate_certificate_authority, default_timeout=None, client_info=client_info, ), - self.create_certificate_authority: gapic_v1.method_async.wrap_method( + self.create_certificate_authority: self._wrap_method( self.create_certificate_authority, default_timeout=None, client_info=client_info, ), - self.disable_certificate_authority: gapic_v1.method_async.wrap_method( + self.disable_certificate_authority: self._wrap_method( self.disable_certificate_authority, default_timeout=None, client_info=client_info, ), - self.enable_certificate_authority: gapic_v1.method_async.wrap_method( + self.enable_certificate_authority: self._wrap_method( self.enable_certificate_authority, default_timeout=None, client_info=client_info, ), - self.fetch_certificate_authority_csr: gapic_v1.method_async.wrap_method( + self.fetch_certificate_authority_csr: self._wrap_method( self.fetch_certificate_authority_csr, default_timeout=None, client_info=client_info, ), - self.get_certificate_authority: gapic_v1.method_async.wrap_method( + self.get_certificate_authority: self._wrap_method( self.get_certificate_authority, default_timeout=None, client_info=client_info, ), - self.list_certificate_authorities: gapic_v1.method_async.wrap_method( + self.list_certificate_authorities: self._wrap_method( self.list_certificate_authorities, default_timeout=None, client_info=client_info, ), - self.undelete_certificate_authority: gapic_v1.method_async.wrap_method( + self.undelete_certificate_authority: self._wrap_method( self.undelete_certificate_authority, default_timeout=None, client_info=client_info, ), - self.delete_certificate_authority: gapic_v1.method_async.wrap_method( + self.delete_certificate_authority: self._wrap_method( self.delete_certificate_authority, default_timeout=None, client_info=client_info, ), - self.update_certificate_authority: gapic_v1.method_async.wrap_method( + self.update_certificate_authority: self._wrap_method( self.update_certificate_authority, default_timeout=None, client_info=client_info, ), - self.create_ca_pool: gapic_v1.method_async.wrap_method( + self.create_ca_pool: self._wrap_method( self.create_ca_pool, default_timeout=None, client_info=client_info, ), - self.update_ca_pool: gapic_v1.method_async.wrap_method( + self.update_ca_pool: self._wrap_method( self.update_ca_pool, default_timeout=None, client_info=client_info, ), - self.get_ca_pool: gapic_v1.method_async.wrap_method( + self.get_ca_pool: self._wrap_method( self.get_ca_pool, default_timeout=None, client_info=client_info, ), - self.list_ca_pools: gapic_v1.method_async.wrap_method( + self.list_ca_pools: self._wrap_method( self.list_ca_pools, default_timeout=None, client_info=client_info, ), - self.delete_ca_pool: gapic_v1.method_async.wrap_method( + self.delete_ca_pool: self._wrap_method( self.delete_ca_pool, default_timeout=None, client_info=client_info, ), - self.fetch_ca_certs: gapic_v1.method_async.wrap_method( + self.fetch_ca_certs: self._wrap_method( self.fetch_ca_certs, default_timeout=None, client_info=client_info, ), - self.get_certificate_revocation_list: gapic_v1.method_async.wrap_method( + self.get_certificate_revocation_list: self._wrap_method( self.get_certificate_revocation_list, default_timeout=None, client_info=client_info, ), - self.list_certificate_revocation_lists: gapic_v1.method_async.wrap_method( + self.list_certificate_revocation_lists: self._wrap_method( self.list_certificate_revocation_lists, default_timeout=None, client_info=client_info, ), - self.update_certificate_revocation_list: gapic_v1.method_async.wrap_method( + self.update_certificate_revocation_list: self._wrap_method( self.update_certificate_revocation_list, default_timeout=None, client_info=client_info, ), - self.create_certificate_template: gapic_v1.method_async.wrap_method( + self.create_certificate_template: self._wrap_method( self.create_certificate_template, default_timeout=None, client_info=client_info, ), - self.delete_certificate_template: gapic_v1.method_async.wrap_method( + self.delete_certificate_template: self._wrap_method( self.delete_certificate_template, default_timeout=None, client_info=client_info, ), - self.get_certificate_template: gapic_v1.method_async.wrap_method( + self.get_certificate_template: self._wrap_method( self.get_certificate_template, default_timeout=None, client_info=client_info, ), - self.list_certificate_templates: gapic_v1.method_async.wrap_method( + self.list_certificate_templates: self._wrap_method( self.list_certificate_templates, default_timeout=None, client_info=client_info, ), - self.update_certificate_template: gapic_v1.method_async.wrap_method( + self.update_certificate_template: self._wrap_method( self.update_certificate_template, default_timeout=None, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py index 70794483bbc8..3a30d9bcff61 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.security.privateca_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCertificateAuthorityServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.security.privateca_v1.types import resources, service - -from .base import CertificateAuthorityServiceTransport -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, @@ -1176,8 +1166,10 @@ class CertificateAuthorityServiceRestStub: _interceptor: CertificateAuthorityServiceRestInterceptor -class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransport): - """REST backend transport for CertificateAuthorityService. +class CertificateAuthorityServiceRestTransport( + _BaseCertificateAuthorityServiceRestTransport +): + """REST backend synchronous transport for CertificateAuthorityService. [Certificate Authority Service][google.cloud.security.privateca.v1.CertificateAuthorityService] @@ -1188,7 +1180,6 @@ class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransp and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -1242,21 +1233,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -1321,19 +1303,37 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ActivateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _ActivateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ActivateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.ActivateCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1364,47 +1364,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:activate", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_activate_certificate_authority( request, metadata ) - pb_request = service.ActivateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._ActivateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1418,21 +1405,35 @@ def __call__( resp = self._interceptor.post_activate_certificate_authority(resp) return resp - class _CreateCaPool(CertificateAuthorityServiceRestStub): + class _CreateCaPool( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCaPool") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "caPoolId": "", - } - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.CreateCaPool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1462,45 +1463,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/caPools", - "body": "ca_pool", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool._get_http_options() + ) request, metadata = self._interceptor.pre_create_ca_pool(request, metadata) - pb_request = service.CreateCaPoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CertificateAuthorityServiceRestTransport._CreateCaPool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1514,19 +1504,35 @@ def __call__( resp = self._interceptor.post_create_ca_pool(resp) return resp - class _CreateCertificate(CertificateAuthorityServiceRestStub): + class _CreateCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.CreateCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1557,47 +1563,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", - "body": "certificate", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_create_certificate( request, metadata ) - pb_request = service.CreateCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._CreateCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1613,21 +1606,37 @@ def __call__( resp = self._interceptor.post_create_certificate(resp) return resp - class _CreateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _CreateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "certificateAuthorityId": "", - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.CreateCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1658,47 +1667,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", - "body": "certificate_authority", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_create_certificate_authority( request, metadata ) - pb_request = service.CreateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._CreateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1712,21 +1708,37 @@ def __call__( resp = self._interceptor.post_create_certificate_authority(resp) return resp - class _CreateCertificateTemplate(CertificateAuthorityServiceRestStub): + class _CreateCertificateTemplate( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCertificateTemplate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "certificateTemplateId": "", - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.CreateCertificateTemplate" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1757,47 +1769,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", - "body": "certificate_template", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate._get_http_options() + ) request, metadata = self._interceptor.pre_create_certificate_template( request, metadata ) - pb_request = service.CreateCertificateTemplateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._CreateCertificateTemplate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1811,19 +1810,34 @@ def __call__( resp = self._interceptor.post_create_certificate_template(resp) return resp - class _DeleteCaPool(CertificateAuthorityServiceRestStub): + class _DeleteCaPool( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCaPool, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("DeleteCaPool") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.DeleteCaPool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1853,38 +1867,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/caPools/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCaPool._get_http_options() + ) request, metadata = self._interceptor.pre_delete_ca_pool(request, metadata) - pb_request = service.DeleteCaPoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCaPool._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCaPool._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + CertificateAuthorityServiceRestTransport._DeleteCaPool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1898,19 +1903,36 @@ def __call__( resp = self._interceptor.post_delete_ca_pool(resp) return resp - class _DeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + class _DeleteCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("DeleteCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.DeleteCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1941,40 +1963,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_delete_certificate_authority( request, metadata ) - pb_request = service.DeleteCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateAuthority._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._DeleteCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1988,19 +1999,36 @@ def __call__( resp = self._interceptor.post_delete_certificate_authority(resp) return resp - class _DeleteCertificateTemplate(CertificateAuthorityServiceRestStub): + class _DeleteCertificateTemplate( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateTemplate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("DeleteCertificateTemplate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.DeleteCertificateTemplate" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2031,40 +2059,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateTemplate._get_http_options() + ) request, metadata = self._interceptor.pre_delete_certificate_template( request, metadata ) - pb_request = service.DeleteCertificateTemplateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateTemplate._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateTemplate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._DeleteCertificateTemplate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2078,19 +2095,37 @@ def __call__( resp = self._interceptor.post_delete_certificate_template(resp) return resp - class _DisableCertificateAuthority(CertificateAuthorityServiceRestStub): + class _DisableCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("DisableCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.DisableCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2121,47 +2156,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:disable", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_disable_certificate_authority( request, metadata ) - pb_request = service.DisableCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._DisableCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2175,19 +2197,37 @@ def __call__( resp = self._interceptor.post_disable_certificate_authority(resp) return resp - class _EnableCertificateAuthority(CertificateAuthorityServiceRestStub): + class _EnableCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("EnableCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.EnableCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2218,47 +2258,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:enable", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_enable_certificate_authority( request, metadata ) - pb_request = service.EnableCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_transcoded_request( + http_options, request + ) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._EnableCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2272,19 +2299,35 @@ def __call__( resp = self._interceptor.post_enable_certificate_authority(resp) return resp - class _FetchCaCerts(CertificateAuthorityServiceRestStub): + class _FetchCaCerts( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("FetchCaCerts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.FetchCaCerts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2313,45 +2356,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{ca_pool=projects/*/locations/*/caPools/*}:fetchCaCerts", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts._get_http_options() + ) request, metadata = self._interceptor.pre_fetch_ca_certs(request, metadata) - pb_request = service.FetchCaCertsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CertificateAuthorityServiceRestTransport._FetchCaCerts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2367,19 +2399,36 @@ def __call__( resp = self._interceptor.post_fetch_ca_certs(resp) return resp - class _FetchCertificateAuthorityCsr(CertificateAuthorityServiceRestStub): + class _FetchCertificateAuthorityCsr( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("FetchCertificateAuthorityCsr") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.FetchCertificateAuthorityCsr" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2409,40 +2458,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:fetch", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_http_options() + ) request, metadata = self._interceptor.pre_fetch_certificate_authority_csr( request, metadata ) - pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._FetchCertificateAuthorityCsr._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2458,19 +2496,34 @@ def __call__( resp = self._interceptor.post_fetch_certificate_authority_csr(resp) return resp - class _GetCaPool(CertificateAuthorityServiceRestStub): + class _GetCaPool( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCaPool, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCaPool") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.GetCaPool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2506,38 +2559,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/caPools/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCaPool._get_http_options() + ) request, metadata = self._interceptor.pre_get_ca_pool(request, metadata) - pb_request = service.GetCaPoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCaPool._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCaPool._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetCaPool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2553,19 +2597,34 @@ def __call__( resp = self._interceptor.post_get_ca_pool(resp) return resp - class _GetCertificate(CertificateAuthorityServiceRestStub): + class _GetCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.GetCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2596,38 +2655,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate(request, metadata) - pb_request = service.GetCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2643,19 +2693,36 @@ def __call__( resp = self._interceptor.post_get_certificate(resp) return resp - class _GetCertificateAuthority(CertificateAuthorityServiceRestStub): + class _GetCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.GetCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2688,40 +2755,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_authority( request, metadata ) - pb_request = service.GetCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2737,19 +2793,36 @@ def __call__( resp = self._interceptor.post_get_certificate_authority(resp) return resp - class _GetCertificateRevocationList(CertificateAuthorityServiceRestStub): + class _GetCertificateRevocationList( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificateRevocationList") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.GetCertificateRevocationList" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2782,40 +2855,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_revocation_list( request, metadata ) - pb_request = service.GetCertificateRevocationListRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetCertificateRevocationList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2831,19 +2893,36 @@ def __call__( resp = self._interceptor.post_get_certificate_revocation_list(resp) return resp - class _GetCertificateTemplate(CertificateAuthorityServiceRestStub): + class _GetCertificateTemplate( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateTemplate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificateTemplate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.GetCertificateTemplate" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2873,40 +2952,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateTemplate._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_template( request, metadata ) - pb_request = service.GetCertificateTemplateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateTemplate._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateTemplate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetCertificateTemplate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2922,19 +2990,34 @@ def __call__( resp = self._interceptor.post_get_certificate_template(resp) return resp - class _ListCaPools(CertificateAuthorityServiceRestStub): + class _ListCaPools( + _BaseCertificateAuthorityServiceRestTransport._BaseListCaPools, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCaPools") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.ListCaPools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2963,38 +3046,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/caPools", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCaPools._get_http_options() + ) request, metadata = self._interceptor.pre_list_ca_pools(request, metadata) - pb_request = service.ListCaPoolsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCaPools._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCaPools._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + CertificateAuthorityServiceRestTransport._ListCaPools._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3010,19 +3084,36 @@ def __call__( resp = self._interceptor.post_list_ca_pools(resp) return resp - class _ListCertificateAuthorities(CertificateAuthorityServiceRestStub): + class _ListCertificateAuthorities( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificateAuthorities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.ListCertificateAuthorities" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -3052,40 +3143,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificate_authorities( request, metadata ) - pb_request = service.ListCertificateAuthoritiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificateAuthorities._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3101,19 +3181,36 @@ def __call__( resp = self._interceptor.post_list_certificate_authorities(resp) return resp - class _ListCertificateRevocationLists(CertificateAuthorityServiceRestStub): + class _ListCertificateRevocationLists( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificateRevocationLists") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.ListCertificateRevocationLists" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -3143,40 +3240,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/caPools/*/certificateAuthorities/*}/certificateRevocationLists", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificate_revocation_lists( request, metadata ) - pb_request = service.ListCertificateRevocationListsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificateRevocationLists._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3192,19 +3278,34 @@ def __call__( resp = self._interceptor.post_list_certificate_revocation_lists(resp) return resp - class _ListCertificates(CertificateAuthorityServiceRestStub): + class _ListCertificates( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificates") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.ListCertificates") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -3233,40 +3334,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificates( request, metadata ) - pb_request = service.ListCertificatesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificates._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3282,19 +3372,36 @@ def __call__( resp = self._interceptor.post_list_certificates(resp) return resp - class _ListCertificateTemplates(CertificateAuthorityServiceRestStub): + class _ListCertificateTemplates( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateTemplates, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificateTemplates") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.ListCertificateTemplates" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -3324,40 +3431,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateTemplates._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificate_templates( request, metadata ) - pb_request = service.ListCertificateTemplatesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateTemplates._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateTemplates._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificateTemplates._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3373,19 +3469,35 @@ def __call__( resp = self._interceptor.post_list_certificate_templates(resp) return resp - class _RevokeCertificate(CertificateAuthorityServiceRestStub): + class _RevokeCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("RevokeCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.RevokeCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3416,47 +3528,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}:revoke", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_revoke_certificate( request, metadata ) - pb_request = service.RevokeCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._RevokeCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3472,19 +3571,37 @@ def __call__( resp = self._interceptor.post_revoke_certificate(resp) return resp - class _UndeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + class _UndeleteCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UndeleteCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "CertificateAuthorityServiceRestTransport.UndeleteCertificateAuthority" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3515,47 +3632,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:undelete", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_undelete_certificate_authority( request, metadata ) - pb_request = service.UndeleteCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UndeleteCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3569,21 +3673,35 @@ def __call__( resp = self._interceptor.post_undelete_certificate_authority(resp) return resp - class _UpdateCaPool(CertificateAuthorityServiceRestStub): + class _UpdateCaPool( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCaPool") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.UpdateCaPool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3613,45 +3731,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{ca_pool.name=projects/*/locations/*/caPools/*}", - "body": "ca_pool", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool._get_http_options() + ) request, metadata = self._interceptor.pre_update_ca_pool(request, metadata) - pb_request = service.UpdateCaPoolRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CertificateAuthorityServiceRestTransport._UpdateCaPool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3665,21 +3772,35 @@ def __call__( resp = self._interceptor.post_update_ca_pool(resp) return resp - class _UpdateCertificate(CertificateAuthorityServiceRestStub): + class _UpdateCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.UpdateCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3710,47 +3831,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{certificate.name=projects/*/locations/*/caPools/*/certificates/*}", - "body": "certificate", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_update_certificate( request, metadata ) - pb_request = service.UpdateCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3766,21 +3874,37 @@ def __call__( resp = self._interceptor.post_update_certificate(resp) return resp - class _UpdateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _UpdateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.UpdateCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3811,47 +3935,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{certificate_authority.name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", - "body": "certificate_authority", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_update_certificate_authority( request, metadata ) - pb_request = service.UpdateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3865,21 +3976,37 @@ def __call__( resp = self._interceptor.post_update_certificate_authority(resp) return resp - class _UpdateCertificateRevocationList(CertificateAuthorityServiceRestStub): + class _UpdateCertificateRevocationList( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificateRevocationList") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.UpdateCertificateRevocationList" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -3910,50 +4037,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{certificate_revocation_list.name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", - "body": "certificate_revocation_list", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_update_certificate_revocation_list( request, metadata ) - pb_request = service.UpdateCertificateRevocationListRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificateRevocationList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3967,21 +4081,37 @@ def __call__( resp = self._interceptor.post_update_certificate_revocation_list(resp) return resp - class _UpdateCertificateTemplate(CertificateAuthorityServiceRestStub): + class _UpdateCertificateTemplate( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificateTemplate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.UpdateCertificateTemplate" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -4012,47 +4142,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{certificate_template.name=projects/*/locations/*/certificateTemplates/*}", - "body": "certificate_template", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate._get_http_options() + ) request, metadata = self._interceptor.pre_update_certificate_template( request, metadata ) - pb_request = service.UpdateCertificateTemplateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificateTemplate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4335,7 +4452,35 @@ def update_certificate_template( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(CertificateAuthorityServiceRestStub): + class _GetLocation( + _BaseCertificateAuthorityServiceRestTransport._BaseGetLocation, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -4359,32 +4504,29 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4392,8 +4534,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -4401,7 +4544,35 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(CertificateAuthorityServiceRestStub): + class _ListLocations( + _BaseCertificateAuthorityServiceRestTransport._BaseListLocations, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -4425,32 +4596,29 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4458,8 +4626,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -4467,7 +4636,35 @@ def __call__( def get_iam_policy(self): return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _GetIamPolicy(CertificateAuthorityServiceRestStub): + class _GetIamPolicy( + _BaseCertificateAuthorityServiceRestTransport._BaseGetIamPolicy, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: iam_policy_pb2.GetIamPolicyRequest, @@ -4491,40 +4688,29 @@ def __call__( policy_pb2.Policy: Response from GetIamPolicy method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:getIamPolicy", - }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:getIamPolicy", - }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:getIamPolicy", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4532,8 +4718,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) return resp @@ -4541,7 +4728,36 @@ def __call__( def set_iam_policy(self): return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _SetIamPolicy(CertificateAuthorityServiceRestStub): + class _SetIamPolicy( + _BaseCertificateAuthorityServiceRestTransport._BaseSetIamPolicy, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: iam_policy_pb2.SetIamPolicyRequest, @@ -4565,45 +4781,34 @@ def __call__( policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:setIamPolicy", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:setIamPolicy", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:setIamPolicy", - "body": "*", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseCertificateAuthorityServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = ( + CertificateAuthorityServiceRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4611,8 +4816,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) return resp @@ -4620,7 +4826,36 @@ def __call__( def test_iam_permissions(self): return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _TestIamPermissions(CertificateAuthorityServiceRestStub): + class _TestIamPermissions( + _BaseCertificateAuthorityServiceRestTransport._BaseTestIamPermissions, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: iam_policy_pb2.TestIamPermissionsRequest, @@ -4644,47 +4879,34 @@ def __call__( iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:testIamPermissions", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:testIamPermissions", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:testIamPermissions", - "body": "*", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseCertificateAuthorityServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = CertificateAuthorityServiceRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4692,8 +4914,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) return resp @@ -4701,7 +4924,36 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(CertificateAuthorityServiceRestStub): + class _CancelOperation( + _BaseCertificateAuthorityServiceRestTransport._BaseCancelOperation, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -4722,37 +4974,36 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseCertificateAuthorityServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = ( + CertificateAuthorityServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4766,7 +5017,35 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(CertificateAuthorityServiceRestStub): + class _DeleteOperation( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteOperation, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -4787,34 +5066,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4828,7 +5104,35 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CertificateAuthorityServiceRestStub): + class _GetOperation( + _BaseCertificateAuthorityServiceRestTransport._BaseGetOperation, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -4852,32 +5156,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4885,8 +5186,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -4894,7 +5196,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CertificateAuthorityServiceRestStub): + class _ListOperations( + _BaseCertificateAuthorityServiceRestTransport._BaseListOperations, + CertificateAuthorityServiceRestStub, + ): + def __hash__(self): + return hash("CertificateAuthorityServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -4918,32 +5248,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + CertificateAuthorityServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4951,8 +5278,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest_base.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest_base.py new file mode 100644 index 000000000000..3e03c6baf711 --- /dev/null +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest_base.py @@ -0,0 +1,1897 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.security.privateca_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO, CertificateAuthorityServiceTransport + + +class _BaseCertificateAuthorityServiceRestTransport( + CertificateAuthorityServiceTransport +): + """Base REST backend transport for CertificateAuthorityService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "privateca.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'privateca.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseActivateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:activate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ActivateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCaPool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "caPoolId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/caPools", + "body": "ca_pool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCaPool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", + "body": "certificate", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateAuthorityId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", + "body": "certificate_authority", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCertificateTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateTemplateId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", + "body": "certificate_template", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateTemplate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCaPool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/caPools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCaPool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCertificateTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseDeleteCertificateTemplate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDisableCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:disable", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DisableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnableCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:enable", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.EnableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchCaCerts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{ca_pool=projects/*/locations/*/caPools/*}:fetchCaCerts", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.FetchCaCertsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCaCerts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchCertificateAuthorityCsr: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:fetch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCaPool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCaPool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateRevocationList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateTemplate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCaPools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/caPools", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCaPoolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCaPools._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificateAuthorities: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificateAuthoritiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificateRevocationLists: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*/certificateAuthorities/*}/certificateRevocationLists", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificateRevocationListsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificates: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificateTemplates: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificateTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateTemplates._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRevokeCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}:revoke", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RevokeCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UndeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUndeleteCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCaPool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{ca_pool.name=projects/*/locations/*/caPools/*}", + "body": "ca_pool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCaPool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate.name=projects/*/locations/*/caPools/*/certificates/*}", + "body": "certificate", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_authority.name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + "body": "certificate_authority", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificateRevocationList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_revocation_list.name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", + "body": "certificate_revocation_list", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificateTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_template.name=projects/*/locations/*/certificateTemplates/*}", + "body": "certificate_template", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateTemplate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCertificateAuthorityServiceRestTransport",) diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/README.rst b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/README.rst new file mode 100644 index 000000000000..7e9a06b69852 --- /dev/null +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CertificateAuthorityServiceTransport` is the ABC for all transports. +- public child `CertificateAuthorityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CertificateAuthorityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCertificateAuthorityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CertificateAuthorityServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/grpc_asyncio.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/grpc_asyncio.py index 6b994c9725b1..2f04d947c6b0 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -892,110 +896,119 @@ def list_reusable_configs( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_certificate: gapic_v1.method_async.wrap_method( + self.create_certificate: self._wrap_method( self.create_certificate, default_timeout=None, client_info=client_info, ), - self.get_certificate: gapic_v1.method_async.wrap_method( + self.get_certificate: self._wrap_method( self.get_certificate, default_timeout=None, client_info=client_info, ), - self.list_certificates: gapic_v1.method_async.wrap_method( + self.list_certificates: self._wrap_method( self.list_certificates, default_timeout=None, client_info=client_info, ), - self.revoke_certificate: gapic_v1.method_async.wrap_method( + self.revoke_certificate: self._wrap_method( self.revoke_certificate, default_timeout=None, client_info=client_info, ), - self.update_certificate: gapic_v1.method_async.wrap_method( + self.update_certificate: self._wrap_method( self.update_certificate, default_timeout=None, client_info=client_info, ), - self.activate_certificate_authority: gapic_v1.method_async.wrap_method( + self.activate_certificate_authority: self._wrap_method( self.activate_certificate_authority, default_timeout=None, client_info=client_info, ), - self.create_certificate_authority: gapic_v1.method_async.wrap_method( + self.create_certificate_authority: self._wrap_method( self.create_certificate_authority, default_timeout=None, client_info=client_info, ), - self.disable_certificate_authority: gapic_v1.method_async.wrap_method( + self.disable_certificate_authority: self._wrap_method( self.disable_certificate_authority, default_timeout=None, client_info=client_info, ), - self.enable_certificate_authority: gapic_v1.method_async.wrap_method( + self.enable_certificate_authority: self._wrap_method( self.enable_certificate_authority, default_timeout=None, client_info=client_info, ), - self.fetch_certificate_authority_csr: gapic_v1.method_async.wrap_method( + self.fetch_certificate_authority_csr: self._wrap_method( self.fetch_certificate_authority_csr, default_timeout=None, client_info=client_info, ), - self.get_certificate_authority: gapic_v1.method_async.wrap_method( + self.get_certificate_authority: self._wrap_method( self.get_certificate_authority, default_timeout=None, client_info=client_info, ), - self.list_certificate_authorities: gapic_v1.method_async.wrap_method( + self.list_certificate_authorities: self._wrap_method( self.list_certificate_authorities, default_timeout=None, client_info=client_info, ), - self.restore_certificate_authority: gapic_v1.method_async.wrap_method( + self.restore_certificate_authority: self._wrap_method( self.restore_certificate_authority, default_timeout=None, client_info=client_info, ), - self.schedule_delete_certificate_authority: gapic_v1.method_async.wrap_method( + self.schedule_delete_certificate_authority: self._wrap_method( self.schedule_delete_certificate_authority, default_timeout=None, client_info=client_info, ), - self.update_certificate_authority: gapic_v1.method_async.wrap_method( + self.update_certificate_authority: self._wrap_method( self.update_certificate_authority, default_timeout=None, client_info=client_info, ), - self.get_certificate_revocation_list: gapic_v1.method_async.wrap_method( + self.get_certificate_revocation_list: self._wrap_method( self.get_certificate_revocation_list, default_timeout=None, client_info=client_info, ), - self.list_certificate_revocation_lists: gapic_v1.method_async.wrap_method( + self.list_certificate_revocation_lists: self._wrap_method( self.list_certificate_revocation_lists, default_timeout=None, client_info=client_info, ), - self.update_certificate_revocation_list: gapic_v1.method_async.wrap_method( + self.update_certificate_revocation_list: self._wrap_method( self.update_certificate_revocation_list, default_timeout=None, client_info=client_info, ), - self.get_reusable_config: gapic_v1.method_async.wrap_method( + self.get_reusable_config: self._wrap_method( self.get_reusable_config, default_timeout=None, client_info=client_info, ), - self.list_reusable_configs: gapic_v1.method_async.wrap_method( + self.list_reusable_configs: self._wrap_method( self.list_reusable_configs, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("CertificateAuthorityServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py index b7758334a100..8c689cdaa571 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py @@ -16,39 +16,29 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.security.privateca_v1beta1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCertificateAuthorityServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.security.privateca_v1beta1.types import resources, service - -from .base import CertificateAuthorityServiceTransport -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, @@ -711,8 +701,10 @@ class CertificateAuthorityServiceRestStub: _interceptor: CertificateAuthorityServiceRestInterceptor -class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransport): - """REST backend transport for CertificateAuthorityService. +class CertificateAuthorityServiceRestTransport( + _BaseCertificateAuthorityServiceRestTransport +): + """REST backend synchronous transport for CertificateAuthorityService. [Certificate Authority Service][google.cloud.security.privateca.v1beta1.CertificateAuthorityService] @@ -723,7 +715,6 @@ class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransp and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -777,21 +768,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -856,19 +838,37 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ActivateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _ActivateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ActivateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.ActivateCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -899,47 +899,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_activate_certificate_authority( request, metadata ) - pb_request = service.ActivateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._ActivateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -953,19 +940,35 @@ def __call__( resp = self._interceptor.post_activate_certificate_authority(resp) return resp - class _CreateCertificate(CertificateAuthorityServiceRestStub): + class _CreateCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.CreateCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -996,47 +999,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", - "body": "certificate", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_create_certificate( request, metadata ) - pb_request = service.CreateCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._CreateCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1052,21 +1042,37 @@ def __call__( resp = self._interceptor.post_create_certificate(resp) return resp - class _CreateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _CreateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "certificateAuthorityId": "", - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.CreateCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1097,47 +1103,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", - "body": "certificate_authority", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_create_certificate_authority( request, metadata ) - pb_request = service.CreateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._CreateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1151,19 +1144,37 @@ def __call__( resp = self._interceptor.post_create_certificate_authority(resp) return resp - class _DisableCertificateAuthority(CertificateAuthorityServiceRestStub): + class _DisableCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("DisableCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.DisableCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1194,47 +1205,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_disable_certificate_authority( request, metadata ) - pb_request = service.DisableCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._DisableCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1248,19 +1246,37 @@ def __call__( resp = self._interceptor.post_disable_certificate_authority(resp) return resp - class _EnableCertificateAuthority(CertificateAuthorityServiceRestStub): + class _EnableCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("EnableCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.EnableCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1291,47 +1307,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_enable_certificate_authority( request, metadata ) - pb_request = service.EnableCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._EnableCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1345,19 +1348,36 @@ def __call__( resp = self._interceptor.post_enable_certificate_authority(resp) return resp - class _FetchCertificateAuthorityCsr(CertificateAuthorityServiceRestStub): + class _FetchCertificateAuthorityCsr( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("FetchCertificateAuthorityCsr") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.FetchCertificateAuthorityCsr" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1387,40 +1407,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_http_options() + ) request, metadata = self._interceptor.pre_fetch_certificate_authority_csr( request, metadata ) - pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._FetchCertificateAuthorityCsr._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1436,19 +1445,34 @@ def __call__( resp = self._interceptor.post_fetch_certificate_authority_csr(resp) return resp - class _GetCertificate(CertificateAuthorityServiceRestStub): + class _GetCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.GetCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1479,38 +1503,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate(request, metadata) - pb_request = service.GetCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + CertificateAuthorityServiceRestTransport._GetCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1526,19 +1541,36 @@ def __call__( resp = self._interceptor.post_get_certificate(resp) return resp - class _GetCertificateAuthority(CertificateAuthorityServiceRestStub): + class _GetCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.GetCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1571,40 +1603,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_authority( request, metadata ) - pb_request = service.GetCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1620,19 +1641,36 @@ def __call__( resp = self._interceptor.post_get_certificate_authority(resp) return resp - class _GetCertificateRevocationList(CertificateAuthorityServiceRestStub): + class _GetCertificateRevocationList( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetCertificateRevocationList") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.GetCertificateRevocationList" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1665,40 +1703,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_http_options() + ) request, metadata = self._interceptor.pre_get_certificate_revocation_list( request, metadata ) - pb_request = service.GetCertificateRevocationListRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetCertificateRevocationList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1714,19 +1741,34 @@ def __call__( resp = self._interceptor.post_get_certificate_revocation_list(resp) return resp - class _GetReusableConfig(CertificateAuthorityServiceRestStub): + class _GetReusableConfig( + _BaseCertificateAuthorityServiceRestTransport._BaseGetReusableConfig, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("GetReusableConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.GetReusableConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1761,40 +1803,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseGetReusableConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_reusable_config( request, metadata ) - pb_request = service.GetReusableConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseGetReusableConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseGetReusableConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._GetReusableConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1810,19 +1841,36 @@ def __call__( resp = self._interceptor.post_get_reusable_config(resp) return resp - class _ListCertificateAuthorities(CertificateAuthorityServiceRestStub): + class _ListCertificateAuthorities( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificateAuthorities") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.ListCertificateAuthorities" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1852,40 +1900,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificate_authorities( request, metadata ) - pb_request = service.ListCertificateAuthoritiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificateAuthorities._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1901,19 +1938,36 @@ def __call__( resp = self._interceptor.post_list_certificate_authorities(resp) return resp - class _ListCertificateRevocationLists(CertificateAuthorityServiceRestStub): + class _ListCertificateRevocationLists( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificateRevocationLists") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.ListCertificateRevocationLists" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1943,40 +1997,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificate_revocation_lists( request, metadata ) - pb_request = service.ListCertificateRevocationListsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificateRevocationLists._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1992,19 +2035,34 @@ def __call__( resp = self._interceptor.post_list_certificate_revocation_lists(resp) return resp - class _ListCertificates(CertificateAuthorityServiceRestStub): + class _ListCertificates( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListCertificates") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.ListCertificates") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2033,40 +2091,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_http_options() + ) request, metadata = self._interceptor.pre_list_certificates( request, metadata ) - pb_request = service.ListCertificatesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListCertificates._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2082,19 +2129,34 @@ def __call__( resp = self._interceptor.post_list_certificates(resp) return resp - class _ListReusableConfigs(CertificateAuthorityServiceRestStub): + class _ListReusableConfigs( + _BaseCertificateAuthorityServiceRestTransport._BaseListReusableConfigs, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ListReusableConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.ListReusableConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2123,40 +2185,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/reusableConfigs", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseListReusableConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_reusable_configs( request, metadata ) - pb_request = service.ListReusableConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseListReusableConfigs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseListReusableConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CertificateAuthorityServiceRestTransport._ListReusableConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2172,19 +2223,37 @@ def __call__( resp = self._interceptor.post_list_reusable_configs(resp) return resp - class _RestoreCertificateAuthority(CertificateAuthorityServiceRestStub): + class _RestoreCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("RestoreCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.RestoreCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2215,47 +2284,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_restore_certificate_authority( request, metadata ) - pb_request = service.RestoreCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._RestoreCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2269,19 +2325,35 @@ def __call__( resp = self._interceptor.post_restore_certificate_authority(resp) return resp - class _RevokeCertificate(CertificateAuthorityServiceRestStub): + class _RevokeCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("RevokeCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.RevokeCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2312,47 +2384,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_revoke_certificate( request, metadata ) - pb_request = service.RevokeCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._RevokeCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2368,19 +2427,37 @@ def __call__( resp = self._interceptor.post_revoke_certificate(resp) return resp - class _ScheduleDeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + class _ScheduleDeleteCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("ScheduleDeleteCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.ScheduleDeleteCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2411,50 +2488,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete", - "body": "*", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_schedule_delete_certificate_authority( request, metadata ) - pb_request = service.ScheduleDeleteCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._ScheduleDeleteCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2468,21 +2532,35 @@ def __call__( resp = self._interceptor.post_schedule_delete_certificate_authority(resp) return resp - class _UpdateCertificate(CertificateAuthorityServiceRestStub): + class _UpdateCertificate( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificate") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CertificateAuthorityServiceRestTransport.UpdateCertificate") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2513,47 +2591,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", - "body": "certificate", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_http_options() + ) request, metadata = self._interceptor.pre_update_certificate( request, metadata ) - pb_request = service.UpdateCertificateRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificate._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2569,21 +2634,37 @@ def __call__( resp = self._interceptor.post_update_certificate(resp) return resp - class _UpdateCertificateAuthority(CertificateAuthorityServiceRestStub): + class _UpdateCertificateAuthority( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.UpdateCertificateAuthority" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2614,47 +2695,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}", - "body": "certificate_authority", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_update_certificate_authority( request, metadata ) - pb_request = service.UpdateCertificateAuthorityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2668,21 +2736,37 @@ def __call__( resp = self._interceptor.post_update_certificate_authority(resp) return resp - class _UpdateCertificateRevocationList(CertificateAuthorityServiceRestStub): + class _UpdateCertificateRevocationList( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList, + CertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("UpdateCertificateRevocationList") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash( + "CertificateAuthorityServiceRestTransport.UpdateCertificateRevocationList" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2713,50 +2797,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", - "body": "certificate_revocation_list", - }, - ] + http_options = ( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_update_certificate_revocation_list( request, metadata ) - pb_request = service.UpdateCertificateRevocationListRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CertificateAuthorityServiceRestTransport._UpdateCertificateRevocationList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest_base.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest_base.py new file mode 100644 index 000000000000..fae3a19dc95c --- /dev/null +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest_base.py @@ -0,0 +1,1152 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.security.privateca_v1beta1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO, CertificateAuthorityServiceTransport + + +class _BaseCertificateAuthorityServiceRestTransport( + CertificateAuthorityServiceTransport +): + """Base REST backend transport for CertificateAuthorityService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "privateca.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'privateca.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseActivateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ActivateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseActivateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", + "body": "certificate", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateAuthorityId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", + "body": "certificate_authority", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseCreateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDisableCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DisableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseDisableCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnableCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.EnableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseEnableCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchCertificateAuthorityCsr: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseFetchCertificateAuthorityCsr._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateRevocationList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetCertificateRevocationList._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetReusableConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetReusableConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseGetReusableConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificateAuthorities: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificateAuthoritiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateAuthorities._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificateRevocationLists: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificateRevocationListsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificateRevocationLists._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCertificates: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCertificatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListCertificates._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListReusableConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/reusableConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListReusableConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseListReusableConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestoreCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RestoreCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseRestoreCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRevokeCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RevokeCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseRevokeCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseScheduleDeleteCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ScheduleDeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseScheduleDeleteCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", + "body": "certificate", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificate._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}", + "body": "certificate_authority", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCertificateRevocationList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", + "body": "certificate_revocation_list", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCertificateAuthorityServiceRestTransport._BaseUpdateCertificateRevocationList._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseCertificateAuthorityServiceRestTransport",) diff --git a/packages/google-cloud-private-ca/setup.py b/packages/google-cloud-private-ca/setup.py index a96f4b54fd6d..e7e79d1cd02a 100644 --- a/packages/google-cloud-private-ca/setup.py +++ b/packages/google-cloud-private-ca/setup.py @@ -49,6 +49,7 @@ "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -91,6 +92,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py index 45657b7d387e..4b6f7e13144d 100644 --- a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py +++ b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -51,16 +68,8 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_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.type import expr_pb2 # type: ignore -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.security.privateca_v1.services.certificate_authority_service import ( CertificateAuthorityServiceAsyncClient, @@ -71,10 +80,24 @@ from google.cloud.security.privateca_v1.types import resources, service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1273,27 +1296,6 @@ def test_create_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_create_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateRequest() - - def test_create_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1369,36 +1371,6 @@ def test_create_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.create_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateRequest() - - @pytest.mark.asyncio async def test_create_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1407,7 +1379,7 @@ async def test_create_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1446,7 +1418,7 @@ async def test_create_certificate_async( transport: str = "grpc_asyncio", request_type=service.CreateCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1526,7 +1498,7 @@ def test_create_certificate_field_headers(): @pytest.mark.asyncio async def test_create_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1610,7 +1582,7 @@ def test_create_certificate_flattened_error(): @pytest.mark.asyncio async def test_create_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1649,7 +1621,7 @@ async def test_create_certificate_flattened_async(): @pytest.mark.asyncio async def test_create_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1710,25 +1682,6 @@ def test_get_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_get_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRequest() - - def test_get_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1792,34 +1745,6 @@ def test_get_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.get_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRequest() - - @pytest.mark.asyncio async def test_get_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1828,7 +1753,7 @@ async def test_get_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1867,7 +1792,7 @@ async def test_get_certificate_async( transport: str = "grpc_asyncio", request_type=service.GetCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1943,7 +1868,7 @@ def test_get_certificate_field_headers(): @pytest.mark.asyncio async def test_get_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2013,7 +1938,7 @@ def test_get_certificate_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2042,7 +1967,7 @@ async def test_get_certificate_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,27 +2019,6 @@ def test_list_certificates(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_certificates_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificates), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificatesRequest() - - def test_list_certificates_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2188,32 +2092,6 @@ def test_list_certificates_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificates_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificates), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificatesRequest() - - @pytest.mark.asyncio async def test_list_certificates_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2222,7 +2100,7 @@ async def test_list_certificates_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2261,7 +2139,7 @@ async def test_list_certificates_async( transport: str = "grpc_asyncio", request_type=service.ListCertificatesRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2333,7 +2211,7 @@ def test_list_certificates_field_headers(): @pytest.mark.asyncio async def test_list_certificates_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2407,7 +2285,7 @@ def test_list_certificates_flattened_error(): @pytest.mark.asyncio async def test_list_certificates_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2438,7 +2316,7 @@ async def test_list_certificates_flattened_async(): @pytest.mark.asyncio async def test_list_certificates_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2552,7 +2430,7 @@ def test_list_certificates_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificates_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2604,7 +2482,7 @@ async def test_list_certificates_async_pager(): @pytest.mark.asyncio async def test_list_certificates_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2701,27 +2579,6 @@ def test_revoke_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_revoke_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.revoke_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.revoke_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RevokeCertificateRequest() - - def test_revoke_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2793,36 +2650,6 @@ def test_revoke_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_revoke_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.revoke_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.revoke_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RevokeCertificateRequest() - - @pytest.mark.asyncio async def test_revoke_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2831,7 +2658,7 @@ async def test_revoke_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2870,7 +2697,7 @@ async def test_revoke_certificate_async( transport: str = "grpc_asyncio", request_type=service.RevokeCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2950,7 +2777,7 @@ def test_revoke_certificate_field_headers(): @pytest.mark.asyncio async def test_revoke_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3024,7 +2851,7 @@ def test_revoke_certificate_flattened_error(): @pytest.mark.asyncio async def test_revoke_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3055,7 +2882,7 @@ async def test_revoke_certificate_flattened_async(): @pytest.mark.asyncio async def test_revoke_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3116,27 +2943,6 @@ def test_update_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_update_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRequest() - - def test_update_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3206,36 +3012,6 @@ def test_update_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.update_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRequest() - - @pytest.mark.asyncio async def test_update_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3244,7 +3020,7 @@ async def test_update_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3283,7 +3059,7 @@ async def test_update_certificate_async( transport: str = "grpc_asyncio", request_type=service.UpdateCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3363,7 +3139,7 @@ def test_update_certificate_field_headers(): @pytest.mark.asyncio async def test_update_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3442,7 +3218,7 @@ def test_update_certificate_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3477,7 +3253,7 @@ async def test_update_certificate_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3525,30 +3301,9 @@ def test_activate_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_activate_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.activate_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.activate_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ActivateCertificateAuthorityRequest() - - -def test_activate_certificate_authority_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_activate_certificate_authority_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -3625,29 +3380,6 @@ def test_activate_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_activate_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.activate_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.activate_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ActivateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_activate_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3656,7 +3388,7 @@ async def test_activate_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3701,7 +3433,7 @@ async def test_activate_certificate_authority_async( request_type=service.ActivateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3768,7 +3500,7 @@ def test_activate_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_activate_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3842,7 +3574,7 @@ def test_activate_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_activate_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3873,7 +3605,7 @@ async def test_activate_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_activate_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3920,27 +3652,6 @@ def test_create_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateAuthorityRequest() - - def test_create_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4020,29 +3731,6 @@ def test_create_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_create_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4051,7 +3739,7 @@ async def test_create_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4096,7 +3784,7 @@ async def test_create_certificate_authority_async( request_type=service.CreateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4163,7 +3851,7 @@ def test_create_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_create_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4247,7 +3935,7 @@ def test_create_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_create_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4286,7 +3974,7 @@ async def test_create_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_create_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4335,27 +4023,6 @@ def test_disable_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_disable_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.disable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DisableCertificateAuthorityRequest() - - def test_disable_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4433,29 +4100,6 @@ def test_disable_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_disable_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.disable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DisableCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_disable_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4464,7 +4108,7 @@ async def test_disable_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4509,7 +4153,7 @@ async def test_disable_certificate_authority_async( request_type=service.DisableCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4576,7 +4220,7 @@ def test_disable_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_disable_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4650,7 +4294,7 @@ def test_disable_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_disable_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4681,7 +4325,7 @@ async def test_disable_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_disable_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4728,27 +4372,6 @@ def test_enable_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_enable_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.enable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EnableCertificateAuthorityRequest() - - def test_enable_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4826,29 +4449,6 @@ def test_enable_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_enable_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.enable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EnableCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_enable_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4857,7 +4457,7 @@ async def test_enable_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4902,7 +4502,7 @@ async def test_enable_certificate_authority_async( request_type=service.EnableCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4969,7 +4569,7 @@ def test_enable_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_enable_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5043,7 +4643,7 @@ def test_enable_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_enable_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5074,7 +4674,7 @@ async def test_enable_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_enable_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5124,27 +4724,6 @@ def test_fetch_certificate_authority_csr(request_type, transport: str = "grpc"): assert response.pem_csr == "pem_csr_value" -def test_fetch_certificate_authority_csr_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_certificate_authority_csr), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_certificate_authority_csr() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCertificateAuthorityCsrRequest() - - def test_fetch_certificate_authority_csr_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5215,31 +4794,6 @@ def test_fetch_certificate_authority_csr_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_fetch_certificate_authority_csr_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_certificate_authority_csr), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.FetchCertificateAuthorityCsrResponse( - pem_csr="pem_csr_value", - ) - ) - response = await client.fetch_certificate_authority_csr() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCertificateAuthorityCsrRequest() - - @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5248,7 +4802,7 @@ async def test_fetch_certificate_authority_csr_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5288,7 +4842,7 @@ async def test_fetch_certificate_authority_csr_async( request_type=service.FetchCertificateAuthorityCsrRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5358,7 +4912,7 @@ def test_fetch_certificate_authority_csr_field_headers(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5432,7 +4986,7 @@ def test_fetch_certificate_authority_csr_flattened_error(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5463,7 +5017,7 @@ async def test_fetch_certificate_authority_csr_flattened_async(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5523,27 +5077,6 @@ def test_get_certificate_authority(request_type, transport: str = "grpc"): assert response.gcs_bucket == "gcs_bucket_value" -def test_get_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateAuthorityRequest() - - def test_get_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5614,36 +5147,6 @@ def test_get_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CertificateAuthority( - name="name_value", - type_=resources.CertificateAuthority.Type.SELF_SIGNED, - tier=resources.CaPool.Tier.ENTERPRISE, - state=resources.CertificateAuthority.State.ENABLED, - pem_ca_certificates=["pem_ca_certificates_value"], - gcs_bucket="gcs_bucket_value", - ) - ) - response = await client.get_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_get_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5652,7 +5155,7 @@ async def test_get_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5691,7 +5194,7 @@ async def test_get_certificate_authority_async( transport: str = "grpc_asyncio", request_type=service.GetCertificateAuthorityRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5771,7 +5274,7 @@ def test_get_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_get_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5845,7 +5348,7 @@ def test_get_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5876,7 +5379,7 @@ async def test_get_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5928,14 +5431,24 @@ def test_list_certificate_authorities(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_certificate_authorities_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_list_certificate_authorities_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListCertificateAuthoritiesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.list_certificate_authorities), "__call__" @@ -5943,38 +5456,7 @@ def test_list_certificate_authorities_empty_call(): call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_certificate_authorities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateAuthoritiesRequest() - - -def test_list_certificate_authorities_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListCertificateAuthoritiesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_authorities), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificate_authorities(request=request) + client.list_certificate_authorities(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.ListCertificateAuthoritiesRequest( @@ -6025,32 +5507,6 @@ def test_list_certificate_authorities_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificate_authorities_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_authorities), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificateAuthoritiesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificate_authorities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateAuthoritiesRequest() - - @pytest.mark.asyncio async def test_list_certificate_authorities_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6059,7 +5515,7 @@ async def test_list_certificate_authorities_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6099,7 +5555,7 @@ async def test_list_certificate_authorities_async( request_type=service.ListCertificateAuthoritiesRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6171,7 +5627,7 @@ def test_list_certificate_authorities_field_headers(): @pytest.mark.asyncio async def test_list_certificate_authorities_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6245,7 +5701,7 @@ def test_list_certificate_authorities_flattened_error(): @pytest.mark.asyncio async def test_list_certificate_authorities_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6276,7 +5732,7 @@ async def test_list_certificate_authorities_flattened_async(): @pytest.mark.asyncio async def test_list_certificate_authorities_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6392,7 +5848,7 @@ def test_list_certificate_authorities_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificate_authorities_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6444,7 +5900,7 @@ async def test_list_certificate_authorities_async_pager(): @pytest.mark.asyncio async def test_list_certificate_authorities_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6527,27 +5983,6 @@ def test_undelete_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_undelete_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.undelete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UndeleteCertificateAuthorityRequest() - - def test_undelete_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6625,29 +6060,6 @@ def test_undelete_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_undelete_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.undelete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UndeleteCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_undelete_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6656,7 +6068,7 @@ async def test_undelete_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6701,7 +6113,7 @@ async def test_undelete_certificate_authority_async( request_type=service.UndeleteCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6768,7 +6180,7 @@ def test_undelete_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_undelete_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6842,7 +6254,7 @@ def test_undelete_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_undelete_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6873,7 +6285,7 @@ async def test_undelete_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_undelete_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6920,27 +6332,6 @@ def test_delete_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCertificateAuthorityRequest() - - def test_delete_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7018,29 +6409,6 @@ def test_delete_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_delete_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7049,7 +6417,7 @@ async def test_delete_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7094,7 +6462,7 @@ async def test_delete_certificate_authority_async( request_type=service.DeleteCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7161,7 +6529,7 @@ def test_delete_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_delete_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7235,7 +6603,7 @@ def test_delete_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_delete_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7266,7 +6634,7 @@ async def test_delete_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_delete_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7313,27 +6681,6 @@ def test_update_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateAuthorityRequest() - - def test_update_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7409,29 +6756,6 @@ def test_update_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_update_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7440,7 +6764,7 @@ async def test_update_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7485,7 +6809,7 @@ async def test_update_certificate_authority_async( request_type=service.UpdateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7552,7 +6876,7 @@ def test_update_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_update_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7631,7 +6955,7 @@ def test_update_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7666,7 +6990,7 @@ async def test_update_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7712,25 +7036,6 @@ def test_create_ca_pool(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_ca_pool_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_ca_pool), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCaPoolRequest() - - def test_create_ca_pool_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7803,27 +7108,6 @@ def test_create_ca_pool_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_ca_pool_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_ca_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCaPoolRequest() - - @pytest.mark.asyncio async def test_create_ca_pool_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7832,7 +7116,7 @@ async def test_create_ca_pool_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7876,7 +7160,7 @@ async def test_create_ca_pool_async( transport: str = "grpc_asyncio", request_type=service.CreateCaPoolRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7939,7 +7223,7 @@ def test_create_ca_pool_field_headers(): @pytest.mark.asyncio async def test_create_ca_pool_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8019,7 +7303,7 @@ def test_create_ca_pool_flattened_error(): @pytest.mark.asyncio async def test_create_ca_pool_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8056,7 +7340,7 @@ async def test_create_ca_pool_flattened_async(): @pytest.mark.asyncio async def test_create_ca_pool_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8103,25 +7387,6 @@ def test_update_ca_pool(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_ca_pool_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_ca_pool), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCaPoolRequest() - - def test_update_ca_pool_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8190,27 +7455,6 @@ def test_update_ca_pool_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_ca_pool_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_ca_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCaPoolRequest() - - @pytest.mark.asyncio async def test_update_ca_pool_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8219,7 +7463,7 @@ async def test_update_ca_pool_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8263,7 +7507,7 @@ async def test_update_ca_pool_async( transport: str = "grpc_asyncio", request_type=service.UpdateCaPoolRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8326,7 +7570,7 @@ def test_update_ca_pool_field_headers(): @pytest.mark.asyncio async def test_update_ca_pool_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8401,7 +7645,7 @@ def test_update_ca_pool_flattened_error(): @pytest.mark.asyncio async def test_update_ca_pool_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8434,7 +7678,7 @@ async def test_update_ca_pool_flattened_async(): @pytest.mark.asyncio async def test_update_ca_pool_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8485,46 +7729,27 @@ def test_get_ca_pool(request_type, transport: str = "grpc"): assert response.tier == resources.CaPool.Tier.ENTERPRISE -def test_get_ca_pool_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_get_ca_pool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetCaPoolRequest( + name="name_value", + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCaPoolRequest() - - -def test_get_ca_pool_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetCaPoolRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_ca_pool(request=request) + client.get_ca_pool(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == service.GetCaPoolRequest( @@ -8567,30 +7792,6 @@ def test_get_ca_pool_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_ca_pool_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CaPool( - name="name_value", - tier=resources.CaPool.Tier.ENTERPRISE, - ) - ) - response = await client.get_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCaPoolRequest() - - @pytest.mark.asyncio async def test_get_ca_pool_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8599,7 +7800,7 @@ async def test_get_ca_pool_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8638,7 +7839,7 @@ async def test_get_ca_pool_async( transport: str = "grpc_asyncio", request_type=service.GetCaPoolRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8706,7 +7907,7 @@ def test_get_ca_pool_field_headers(): @pytest.mark.asyncio async def test_get_ca_pool_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8774,7 +7975,7 @@ def test_get_ca_pool_flattened_error(): @pytest.mark.asyncio async def test_get_ca_pool_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8801,7 +8002,7 @@ async def test_get_ca_pool_flattened_async(): @pytest.mark.asyncio async def test_get_ca_pool_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8851,25 +8052,6 @@ def test_list_ca_pools(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_ca_pools_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_ca_pools), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_ca_pools() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCaPoolsRequest() - - def test_list_ca_pools_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8939,30 +8121,6 @@ def test_list_ca_pools_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_ca_pools_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_ca_pools), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCaPoolsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_ca_pools() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCaPoolsRequest() - - @pytest.mark.asyncio async def test_list_ca_pools_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8971,7 +8129,7 @@ async def test_list_ca_pools_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9010,7 +8168,7 @@ async def test_list_ca_pools_async( transport: str = "grpc_asyncio", request_type=service.ListCaPoolsRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9078,7 +8236,7 @@ def test_list_ca_pools_field_headers(): @pytest.mark.asyncio async def test_list_ca_pools_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9148,7 +8306,7 @@ def test_list_ca_pools_flattened_error(): @pytest.mark.asyncio async def test_list_ca_pools_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9177,7 +8335,7 @@ async def test_list_ca_pools_flattened_async(): @pytest.mark.asyncio async def test_list_ca_pools_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9287,7 +8445,7 @@ def test_list_ca_pools_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_ca_pools_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9337,7 +8495,7 @@ async def test_list_ca_pools_async_pager(): @pytest.mark.asyncio async def test_list_ca_pools_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9416,25 +8574,6 @@ def test_delete_ca_pool(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_ca_pool_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_ca_pool), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCaPoolRequest() - - def test_delete_ca_pool_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -9505,27 +8644,6 @@ def test_delete_ca_pool_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_ca_pool_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_ca_pool), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_ca_pool() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCaPoolRequest() - - @pytest.mark.asyncio async def test_delete_ca_pool_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -9534,7 +8652,7 @@ async def test_delete_ca_pool_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9578,7 +8696,7 @@ async def test_delete_ca_pool_async( transport: str = "grpc_asyncio", request_type=service.DeleteCaPoolRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9641,7 +8759,7 @@ def test_delete_ca_pool_field_headers(): @pytest.mark.asyncio async def test_delete_ca_pool_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9711,7 +8829,7 @@ def test_delete_ca_pool_flattened_error(): @pytest.mark.asyncio async def test_delete_ca_pool_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9740,7 +8858,7 @@ async def test_delete_ca_pool_flattened_async(): @pytest.mark.asyncio async def test_delete_ca_pool_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9785,25 +8903,6 @@ def test_fetch_ca_certs(request_type, transport: str = "grpc"): assert isinstance(response, service.FetchCaCertsResponse) -def test_fetch_ca_certs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_ca_certs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_ca_certs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCaCertsRequest() - - def test_fetch_ca_certs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -9869,27 +8968,6 @@ def test_fetch_ca_certs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_fetch_ca_certs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_ca_certs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.FetchCaCertsResponse() - ) - response = await client.fetch_ca_certs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCaCertsRequest() - - @pytest.mark.asyncio async def test_fetch_ca_certs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -9898,7 +8976,7 @@ async def test_fetch_ca_certs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9937,7 +9015,7 @@ async def test_fetch_ca_certs_async( transport: str = "grpc_asyncio", request_type=service.FetchCaCertsRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10000,7 +9078,7 @@ def test_fetch_ca_certs_field_headers(): @pytest.mark.asyncio async def test_fetch_ca_certs_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10070,7 +9148,7 @@ def test_fetch_ca_certs_flattened_error(): @pytest.mark.asyncio async def test_fetch_ca_certs_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -10099,7 +9177,7 @@ async def test_fetch_ca_certs_flattened_async(): @pytest.mark.asyncio async def test_fetch_ca_certs_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -10159,27 +9237,6 @@ def test_get_certificate_revocation_list(request_type, transport: str = "grpc"): assert response.revision_id == "revision_id_value" -def test_get_certificate_revocation_list_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_revocation_list), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRevocationListRequest() - - def test_get_certificate_revocation_list_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -10250,36 +9307,6 @@ def test_get_certificate_revocation_list_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_revocation_list_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_revocation_list), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CertificateRevocationList( - name="name_value", - sequence_number=1601, - pem_crl="pem_crl_value", - access_url="access_url_value", - state=resources.CertificateRevocationList.State.ACTIVE, - revision_id="revision_id_value", - ) - ) - response = await client.get_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRevocationListRequest() - - @pytest.mark.asyncio async def test_get_certificate_revocation_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -10288,7 +9315,7 @@ async def test_get_certificate_revocation_list_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10328,7 +9355,7 @@ async def test_get_certificate_revocation_list_async( request_type=service.GetCertificateRevocationListRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10408,7 +9435,7 @@ def test_get_certificate_revocation_list_field_headers(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10482,7 +9509,7 @@ def test_get_certificate_revocation_list_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -10513,7 +9540,7 @@ async def test_get_certificate_revocation_list_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -10565,27 +9592,6 @@ def test_list_certificate_revocation_lists(request_type, transport: str = "grpc" assert response.unreachable == ["unreachable_value"] -def test_list_certificate_revocation_lists_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_revocation_lists), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificate_revocation_lists() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateRevocationListsRequest() - - def test_list_certificate_revocation_lists_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -10662,32 +9668,6 @@ def test_list_certificate_revocation_lists_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificate_revocation_lists_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_revocation_lists), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificateRevocationListsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificate_revocation_lists() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateRevocationListsRequest() - - @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -10696,7 +9676,7 @@ async def test_list_certificate_revocation_lists_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10736,7 +9716,7 @@ async def test_list_certificate_revocation_lists_async( request_type=service.ListCertificateRevocationListsRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10808,7 +9788,7 @@ def test_list_certificate_revocation_lists_field_headers(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10882,7 +9862,7 @@ def test_list_certificate_revocation_lists_flattened_error(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -10913,7 +9893,7 @@ async def test_list_certificate_revocation_lists_flattened_async(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -11029,7 +10009,7 @@ def test_list_certificate_revocation_lists_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -11083,7 +10063,7 @@ async def test_list_certificate_revocation_lists_async_pager(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -11166,30 +10146,9 @@ def test_update_certificate_revocation_list(request_type, transport: str = "grpc assert isinstance(response, future.Future) -def test_update_certificate_revocation_list_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_revocation_list), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRevocationListRequest() - - -def test_update_certificate_revocation_list_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_update_certificate_revocation_list_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -11262,29 +10221,6 @@ def test_update_certificate_revocation_list_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_revocation_list_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_revocation_list), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRevocationListRequest() - - @pytest.mark.asyncio async def test_update_certificate_revocation_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -11293,7 +10229,7 @@ async def test_update_certificate_revocation_list_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11338,7 +10274,7 @@ async def test_update_certificate_revocation_list_async( request_type=service.UpdateCertificateRevocationListRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11405,7 +10341,7 @@ def test_update_certificate_revocation_list_field_headers(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11488,7 +10424,7 @@ def test_update_certificate_revocation_list_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -11525,7 +10461,7 @@ async def test_update_certificate_revocation_list_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -11575,27 +10511,6 @@ def test_create_certificate_template(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_certificate_template_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_template), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateTemplateRequest() - - def test_create_certificate_template_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -11675,29 +10590,6 @@ def test_create_certificate_template_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_certificate_template_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_template), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateTemplateRequest() - - @pytest.mark.asyncio async def test_create_certificate_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -11706,7 +10598,7 @@ async def test_create_certificate_template_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11751,7 +10643,7 @@ async def test_create_certificate_template_async( request_type=service.CreateCertificateTemplateRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11818,7 +10710,7 @@ def test_create_certificate_template_field_headers(): @pytest.mark.asyncio async def test_create_certificate_template_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11902,7 +10794,7 @@ def test_create_certificate_template_flattened_error(): @pytest.mark.asyncio async def test_create_certificate_template_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -11941,7 +10833,7 @@ async def test_create_certificate_template_flattened_async(): @pytest.mark.asyncio async def test_create_certificate_template_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -11990,27 +10882,6 @@ def test_delete_certificate_template(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_certificate_template_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_certificate_template), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCertificateTemplateRequest() - - def test_delete_certificate_template_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -12088,29 +10959,6 @@ def test_delete_certificate_template_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_certificate_template_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_certificate_template), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteCertificateTemplateRequest() - - @pytest.mark.asyncio async def test_delete_certificate_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -12119,7 +10967,7 @@ async def test_delete_certificate_template_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12164,7 +11012,7 @@ async def test_delete_certificate_template_async( request_type=service.DeleteCertificateTemplateRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12231,7 +11079,7 @@ def test_delete_certificate_template_field_headers(): @pytest.mark.asyncio async def test_delete_certificate_template_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -12305,7 +11153,7 @@ def test_delete_certificate_template_flattened_error(): @pytest.mark.asyncio async def test_delete_certificate_template_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -12336,7 +11184,7 @@ async def test_delete_certificate_template_flattened_async(): @pytest.mark.asyncio async def test_delete_certificate_template_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -12388,27 +11236,6 @@ def test_get_certificate_template(request_type, transport: str = "grpc"): assert response.description == "description_value" -def test_get_certificate_template_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_template), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateTemplateRequest() - - def test_get_certificate_template_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -12479,32 +11306,6 @@ def test_get_certificate_template_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_template_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_template), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CertificateTemplate( - name="name_value", - description="description_value", - ) - ) - response = await client.get_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateTemplateRequest() - - @pytest.mark.asyncio async def test_get_certificate_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -12513,7 +11314,7 @@ async def test_get_certificate_template_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12552,7 +11353,7 @@ async def test_get_certificate_template_async( transport: str = "grpc_asyncio", request_type=service.GetCertificateTemplateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12624,7 +11425,7 @@ def test_get_certificate_template_field_headers(): @pytest.mark.asyncio async def test_get_certificate_template_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -12698,7 +11499,7 @@ def test_get_certificate_template_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_template_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -12729,7 +11530,7 @@ async def test_get_certificate_template_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_template_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -12781,27 +11582,6 @@ def test_list_certificate_templates(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_certificate_templates_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_templates), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificate_templates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateTemplatesRequest() - - def test_list_certificate_templates_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -12878,32 +11658,6 @@ def test_list_certificate_templates_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificate_templates_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_templates), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificateTemplatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificate_templates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateTemplatesRequest() - - @pytest.mark.asyncio async def test_list_certificate_templates_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -12912,7 +11666,7 @@ async def test_list_certificate_templates_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12952,7 +11706,7 @@ async def test_list_certificate_templates_async( request_type=service.ListCertificateTemplatesRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13024,7 +11778,7 @@ def test_list_certificate_templates_field_headers(): @pytest.mark.asyncio async def test_list_certificate_templates_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13098,7 +11852,7 @@ def test_list_certificate_templates_flattened_error(): @pytest.mark.asyncio async def test_list_certificate_templates_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -13129,7 +11883,7 @@ async def test_list_certificate_templates_flattened_async(): @pytest.mark.asyncio async def test_list_certificate_templates_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -13245,7 +11999,7 @@ def test_list_certificate_templates_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificate_templates_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -13297,7 +12051,7 @@ async def test_list_certificate_templates_async_pager(): @pytest.mark.asyncio async def test_list_certificate_templates_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -13380,27 +12134,6 @@ def test_update_certificate_template(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_certificate_template_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_template), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateTemplateRequest() - - def test_update_certificate_template_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -13476,29 +12209,6 @@ def test_update_certificate_template_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_template_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_template), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_certificate_template() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateTemplateRequest() - - @pytest.mark.asyncio async def test_update_certificate_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -13507,7 +12217,7 @@ async def test_update_certificate_template_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13552,7 +12262,7 @@ async def test_update_certificate_template_async( request_type=service.UpdateCertificateTemplateRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13619,7 +12329,7 @@ def test_update_certificate_template_field_headers(): @pytest.mark.asyncio async def test_update_certificate_template_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13698,7 +12408,7 @@ def test_update_certificate_template_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_template_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -13733,7 +12443,7 @@ async def test_update_certificate_template_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_template_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -13746,262 +12456,6 @@ async def test_update_certificate_template_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCertificateRequest, - dict, - ], -) -def test_create_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} - request_init["certificate"] = { - "name": "name_value", - "pem_csr": "pem_csr_value", - "config": { - "subject_config": { - "subject": { - "common_name": "common_name_value", - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "x509_config": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": {}, - }, - "public_key": {"key": b"key_blob", "format_": 1}, - "subject_key_id": {"key_id": "key_id_value"}, - }, - "issuer_certificate_authority": "issuer_certificate_authority_value", - "lifetime": {"seconds": 751, "nanos": 543}, - "certificate_template": "certificate_template_value", - "subject_mode": 1, - "revocation_details": { - "revocation_state": 1, - "revocation_time": {"seconds": 751, "nanos": 543}, - }, - "pem_certificate": "pem_certificate_value", - "certificate_description": { - "subject_description": { - "subject": {}, - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {}, - "not_after_time": {}, - }, - "x509_description": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - }, - "pem_certificate_chain": [ - "pem_certificate_chain_value1", - "pem_certificate_chain_value2", - ], - "create_time": {}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCertificateRequest.meta.fields["certificate"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["certificate"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate"][field])): - del request_init["certificate"][field][i][subfield] - else: - del request_init["certificate"][field][subfield] - 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 = resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.issuer_certificate_authority == "issuer_certificate_authority_value" - assert response.certificate_template == "certificate_template_value" - assert response.subject_mode == resources.SubjectRequestMode.DEFAULT - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - - def test_create_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -14150,91 +12604,10 @@ def test_create_certificate_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_create_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCertificateRequest.pb( - service.CreateCertificateRequest() - ) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.CreateCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.create_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_certificate_rest_bad_request( - transport: str = "rest", request_type=service.CreateCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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.create_certificate(request) - - -def test_create_certificate_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -14294,65 +12667,6 @@ def test_create_certificate_rest_flattened_error(transport: str = "rest"): ) -def test_create_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCertificateRequest, - dict, - ], -) -def test_get_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - 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 = resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.issuer_certificate_authority == "issuer_certificate_authority_value" - assert response.certificate_template == "certificate_template_value" - assert response.subject_mode == resources.SubjectRequestMode.DEFAULT - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - - def test_get_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -14472,87 +12786,6 @@ def test_get_certificate_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.GetCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.get_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_certificate_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - 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_certificate(request) - - def test_get_certificate_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14612,54 +12845,6 @@ def test_get_certificate_rest_flattened_error(transport: str = "rest"): ) -def test_get_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificatesRequest, - dict, - ], -) -def test_list_certificates_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = service.ListCertificatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_certificates(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificatesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_certificates_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -14800,91 +12985,10 @@ def test_list_certificates_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificates_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_list_certificates_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCertificatesRequest.pb( - service.ListCertificatesRequest() - ) - 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 = service.ListCertificatesResponse.to_json( - service.ListCertificatesResponse() - ) - - request = service.ListCertificatesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCertificatesResponse() - - client.list_certificates( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_certificates_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificatesRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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.list_certificates(request) - - -def test_list_certificates_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -15003,59 +13107,6 @@ def test_list_certificates_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.RevokeCertificateRequest, - dict, - ], -) -def test_revoke_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - 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 = resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.revoke_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.issuer_certificate_authority == "issuer_certificate_authority_value" - assert response.certificate_template == "certificate_template_value" - assert response.subject_mode == resources.SubjectRequestMode.DEFAULT - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - - def test_revoke_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -15188,89 +13239,6 @@ def test_revoke_certificate_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_revoke_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.RevokeCertificateRequest.pb( - service.RevokeCertificateRequest() - ) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.RevokeCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.revoke_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_revoke_certificate_rest_bad_request( - transport: str = "rest", request_type=service.RevokeCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - 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.revoke_certificate(request) - - def test_revoke_certificate_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15330,289 +13298,23 @@ def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): ) -def test_revoke_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_certificate_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCertificateRequest, - dict, - ], -) -def test_update_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - } - request_init["certificate"] = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4", - "pem_csr": "pem_csr_value", - "config": { - "subject_config": { - "subject": { - "common_name": "common_name_value", - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "x509_config": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": {}, - }, - "public_key": {"key": b"key_blob", "format_": 1}, - "subject_key_id": {"key_id": "key_id_value"}, - }, - "issuer_certificate_authority": "issuer_certificate_authority_value", - "lifetime": {"seconds": 751, "nanos": 543}, - "certificate_template": "certificate_template_value", - "subject_mode": 1, - "revocation_details": { - "revocation_state": 1, - "revocation_time": {"seconds": 751, "nanos": 543}, - }, - "pem_certificate": "pem_certificate_value", - "certificate_description": { - "subject_description": { - "subject": {}, - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {}, - "not_after_time": {}, - }, - "x509_description": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - }, - "pem_certificate_chain": [ - "pem_certificate_chain_value1", - "pem_certificate_chain_value2", - ], - "create_time": {}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateRequest.meta.fields["certificate"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["certificate"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate"][field])): - del request_init["certificate"][field][i][subfield] - else: - del request_init["certificate"][field][subfield] - 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 = resources.Certificate( - name="name_value", - issuer_certificate_authority="issuer_certificate_authority_value", - certificate_template="certificate_template_value", - subject_mode=resources.SubjectRequestMode.DEFAULT, - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.issuer_certificate_authority == "issuer_certificate_authority_value" - assert response.certificate_template == "certificate_template_value" - assert response.subject_mode == resources.SubjectRequestMode.DEFAULT - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - - -def test_update_certificate_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_certificate in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_certificate in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -15735,95 +13437,10 @@ def test_update_certificate_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_update_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCertificateRequest.pb( - service.UpdateCertificateRequest() - ) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.UpdateCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.update_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_certificate_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" - } - } - 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_certificate(request) - - -def test_update_certificate_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -15883,49 +13500,6 @@ def test_update_certificate_rest_flattened_error(transport: str = "rest"): ) -def test_update_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ActivateCertificateAuthorityRequest, - dict, - ], -) -def test_activate_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.activate_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -16067,93 +13641,6 @@ def test_activate_certificate_authority_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_activate_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_activate_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_activate_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ActivateCertificateAuthorityRequest.pb( - service.ActivateCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.ActivateCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.activate_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_activate_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.ActivateCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.activate_certificate_authority(request) - - def test_activate_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16211,290 +13698,24 @@ def test_activate_certificate_authority_rest_flattened_error(transport: str = "r ) -def test_activate_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCertificateAuthorityRequest, - dict, - ], -) -def test_create_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} - request_init["certificate_authority"] = { - "name": "name_value", - "type_": 1, - "config": { - "subject_config": { - "subject": { - "common_name": "common_name_value", - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "x509_config": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": {}, - }, - "public_key": {"key": b"key_blob", "format_": 1}, - "subject_key_id": {"key_id": "key_id_value"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "key_spec": { - "cloud_kms_key_version": "cloud_kms_key_version_value", - "algorithm": 1, - }, - "subordinate_config": { - "certificate_authority": "certificate_authority_value", - "pem_issuer_chain": { - "pem_certificates": [ - "pem_certificates_value1", - "pem_certificates_value2", - ] - }, - }, - "tier": 1, - "state": 1, - "pem_ca_certificates": [ - "pem_ca_certificates_value1", - "pem_ca_certificates_value2", - ], - "ca_certificate_descriptions": [ - { - "subject_description": { - "subject": {}, - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {"seconds": 751, "nanos": 543}, - "not_after_time": {}, - }, - "x509_description": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - } - ], - "gcs_bucket": "gcs_bucket_value", - "access_urls": { - "ca_certificate_access_url": "ca_certificate_access_url_value", - "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], - }, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "expire_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCertificateAuthorityRequest.meta.fields[ - "certificate_authority" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_authority" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_authority"][field])): - del request_init["certificate_authority"][field][i][subfield] - else: - del request_init["certificate_authority"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_certificate_authority - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.create_certificate_authority + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -16642,95 +13863,10 @@ def test_create_certificate_authority_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_create_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_create_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_create_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCertificateAuthorityRequest.pb( - service.CreateCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.CreateCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.CreateCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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.create_certificate_authority(request) - - -def test_create_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -16788,49 +13924,6 @@ def test_create_certificate_authority_rest_flattened_error(transport: str = "res ) -def test_create_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.DisableCertificateAuthorityRequest, - dict, - ], -) -def test_disable_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.disable_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_disable_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -16959,93 +14052,6 @@ def test_disable_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_disable_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_disable_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DisableCertificateAuthorityRequest.pb( - service.DisableCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.DisableCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.disable_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_disable_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.DisableCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.disable_certificate_authority(request) - - def test_disable_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17103,49 +14109,6 @@ def test_disable_certificate_authority_rest_flattened_error(transport: str = "re ) -def test_disable_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.EnableCertificateAuthorityRequest, - dict, - ], -) -def test_enable_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.enable_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_enable_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -17272,97 +14235,10 @@ def test_enable_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_enable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_enable_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_enable_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.EnableCertificateAuthorityRequest.pb( - service.EnableCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.EnableCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enable_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enable_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.EnableCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.enable_certificate_authority(request) - - -def test_enable_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -17416,54 +14292,6 @@ def test_enable_certificate_authority_rest_flattened_error(transport: str = "res ) -def test_enable_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.FetchCertificateAuthorityCsrRequest, - dict, - ], -) -def test_fetch_certificate_authority_csr_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = service.FetchCertificateAuthorityCsrResponse( - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.fetch_certificate_authority_csr(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) - assert response.pem_csr == "pem_csr_value" - - def test_fetch_certificate_authority_csr_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -17590,93 +14418,6 @@ def test_fetch_certificate_authority_csr_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_fetch_certificate_authority_csr", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_fetch_certificate_authority_csr", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.FetchCertificateAuthorityCsrRequest.pb( - service.FetchCertificateAuthorityCsrRequest() - ) - 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 = ( - service.FetchCertificateAuthorityCsrResponse.to_json( - service.FetchCertificateAuthorityCsrResponse() - ) - ) - - request = service.FetchCertificateAuthorityCsrRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.FetchCertificateAuthorityCsrResponse() - - client.fetch_certificate_authority_csr( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_certificate_authority_csr_rest_bad_request( - transport: str = "rest", request_type=service.FetchCertificateAuthorityCsrRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.fetch_certificate_authority_csr(request) - - def test_fetch_certificate_authority_csr_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17736,64 +14477,6 @@ def test_fetch_certificate_authority_csr_rest_flattened_error(transport: str = " ) -def test_fetch_certificate_authority_csr_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCertificateAuthorityRequest, - dict, - ], -) -def test_get_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = resources.CertificateAuthority( - name="name_value", - type_=resources.CertificateAuthority.Type.SELF_SIGNED, - tier=resources.CaPool.Tier.ENTERPRISE, - state=resources.CertificateAuthority.State.ENABLED, - pem_ca_certificates=["pem_ca_certificates_value"], - gcs_bucket="gcs_bucket_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CertificateAuthority) - assert response.name == "name_value" - assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED - assert response.tier == resources.CaPool.Tier.ENTERPRISE - assert response.state == resources.CertificateAuthority.State.ENABLED - assert response.pem_ca_certificates == ["pem_ca_certificates_value"] - assert response.gcs_bucket == "gcs_bucket_value" - - def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -17918,95 +14601,10 @@ def test_get_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_get_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_get_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_get_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCertificateAuthorityRequest.pb( - service.GetCertificateAuthorityRequest() - ) - 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 = resources.CertificateAuthority.to_json( - resources.CertificateAuthority() - ) - - request = service.GetCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CertificateAuthority() - - client.get_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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_certificate_authority(request) - - -def test_get_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -18062,54 +14660,6 @@ def test_get_certificate_authority_rest_flattened_error(transport: str = "rest") ) -def test_get_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificateAuthoritiesRequest, - dict, - ], -) -def test_list_certificate_authorities_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = service.ListCertificateAuthoritiesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_certificate_authorities(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificateAuthoritiesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_certificate_authorities_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -18253,89 +14803,6 @@ def test_list_certificate_authorities_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificate_authorities_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_list_certificate_authorities", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_list_certificate_authorities", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCertificateAuthoritiesRequest.pb( - service.ListCertificateAuthoritiesRequest() - ) - 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 = service.ListCertificateAuthoritiesResponse.to_json( - service.ListCertificateAuthoritiesResponse() - ) - - request = service.ListCertificateAuthoritiesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCertificateAuthoritiesResponse() - - client.list_certificate_authorities( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_certificate_authorities_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificateAuthoritiesRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/caPools/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.list_certificate_authorities(request) - - def test_list_certificate_authorities_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18460,43 +14927,6 @@ def test_list_certificate_authorities_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.UndeleteCertificateAuthorityRequest, - dict, - ], -) -def test_undelete_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.undelete_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_undelete_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -18625,97 +15055,10 @@ def test_undelete_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_undelete_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_undelete_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_undelete_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UndeleteCertificateAuthorityRequest.pb( - service.UndeleteCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.UndeleteCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undelete_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.UndeleteCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.undelete_certificate_authority(request) - - -def test_undelete_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -18769,49 +15112,6 @@ def test_undelete_certificate_authority_rest_flattened_error(transport: str = "r ) -def test_undelete_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.DeleteCertificateAuthorityRequest, - dict, - ], -) -def test_delete_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -18956,93 +15256,6 @@ def test_delete_certificate_authority_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_delete_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_delete_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteCertificateAuthorityRequest.pb( - service.DeleteCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.DeleteCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.DeleteCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.delete_certificate_authority(request) - - def test_delete_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19100,294 +15313,24 @@ def test_delete_certificate_authority_rest_flattened_error(transport: str = "res ) -def test_delete_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCertificateAuthorityRequest, - dict, - ], -) -def test_update_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_authority": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - } - request_init["certificate_authority"] = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4", - "type_": 1, - "config": { - "subject_config": { - "subject": { - "common_name": "common_name_value", - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "x509_config": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": {}, - }, - "public_key": {"key": b"key_blob", "format_": 1}, - "subject_key_id": {"key_id": "key_id_value"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "key_spec": { - "cloud_kms_key_version": "cloud_kms_key_version_value", - "algorithm": 1, - }, - "subordinate_config": { - "certificate_authority": "certificate_authority_value", - "pem_issuer_chain": { - "pem_certificates": [ - "pem_certificates_value1", - "pem_certificates_value2", - ] - }, - }, - "tier": 1, - "state": 1, - "pem_ca_certificates": [ - "pem_ca_certificates_value1", - "pem_ca_certificates_value2", - ], - "ca_certificate_descriptions": [ - { - "subject_description": { - "subject": {}, - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {"seconds": 751, "nanos": 543}, - "not_after_time": {}, - }, - "x509_description": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - } - ], - "gcs_bucket": "gcs_bucket_value", - "access_urls": { - "ca_certificate_access_url": "ca_certificate_access_url_value", - "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], - }, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "expire_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateAuthorityRequest.meta.fields[ - "certificate_authority" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_authority" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_authority"][field])): - del request_init["certificate_authority"][field][i][subfield] - else: - del request_init["certificate_authority"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_certificate_authority - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_certificate_authority + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -19511,99 +15454,10 @@ def test_update_certificate_authority_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_update_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_update_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_update_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCertificateAuthorityRequest.pb( - service.UpdateCertificateAuthorityRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.UpdateCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_authority": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - } - 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_certificate_authority(request) - - -def test_update_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -19661,258 +15515,48 @@ def test_update_certificate_authority_rest_flattened_error(transport: str = "res ) -def test_update_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_ca_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCaPoolRequest, - dict, - ], -) -def test_create_ca_pool_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.create_ca_pool in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["ca_pool"] = { - "name": "name_value", - "tier": 1, - "issuance_policy": { - "allowed_key_types": [ - { - "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, - "elliptic_curve": {"signature_algorithm": 1}, - } - ], - "maximum_lifetime": {"seconds": 751, "nanos": 543}, - "allowed_issuance_modes": { - "allow_csr_based_issuance": True, - "allow_config_based_issuance": True, - }, - "baseline_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": [ - {"object_id": {}, "critical": True, "value": b"value_blob"} - ], - }, - "identity_constraints": { - "cel_expression": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - "allow_subject_passthrough": True, - "allow_subject_alt_names_passthrough": True, - }, - "passthrough_extensions": { - "known_extensions": [1], - "additional_extensions": {}, - }, - }, - "publishing_options": { - "publish_ca_cert": True, - "publish_crl": True, - "encoding_format": 1, - }, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_ca_pool] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCaPoolRequest.meta.fields["ca_pool"] + request = {} + client.create_ca_pool(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.create_ca_pool(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ca_pool"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ca_pool"][field])): - del request_init["ca_pool"][field][i][subfield] - else: - del request_init["ca_pool"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_ca_pool(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_ca_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_ca_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_ca_pool] = mock_rpc - - request = {} - client.create_ca_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_ca_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_ca_pool_rest_required_fields(request_type=service.CreateCaPoolRequest): - transport_class = transports.CertificateAuthorityServiceRestTransport +def test_create_ca_pool_rest_required_fields(request_type=service.CreateCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} request_init["parent"] = "" @@ -20024,87 +15668,6 @@ def test_create_ca_pool_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_ca_pool_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "post_create_ca_pool" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_create_ca_pool" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCaPoolRequest.pb(service.CreateCaPoolRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.CreateCaPoolRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_ca_pool( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_ca_pool_rest_bad_request( - transport: str = "rest", request_type=service.CreateCaPoolRequest -): - client = CertificateAuthorityServiceClient( - 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.create_ca_pool(request) - - def test_create_ca_pool_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20163,296 +15726,84 @@ def test_create_ca_pool_rest_flattened_error(transport: str = "rest"): ) -def test_create_ca_pool_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_ca_pool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_ca_pool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_ca_pool] = mock_rpc + + request = {} + client.update_ca_pool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_ca_pool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_ca_pool_rest_required_fields(request_type=service.UpdateCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_ca_pool._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_ca_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCaPoolRequest, - dict, - ], -) -def test_update_ca_pool_rest(request_type): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - - # send a request that will satisfy transcoding - request_init = { - "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/sample3"} - } - request_init["ca_pool"] = { - "name": "projects/sample1/locations/sample2/caPools/sample3", - "tier": 1, - "issuance_policy": { - "allowed_key_types": [ - { - "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, - "elliptic_curve": {"signature_algorithm": 1}, - } - ], - "maximum_lifetime": {"seconds": 751, "nanos": 543}, - "allowed_issuance_modes": { - "allow_csr_based_issuance": True, - "allow_config_based_issuance": True, - }, - "baseline_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": [ - "permitted_uris_value1", - "permitted_uris_value2", - ], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": [ - {"object_id": {}, "critical": True, "value": b"value_blob"} - ], - }, - "identity_constraints": { - "cel_expression": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - "allow_subject_passthrough": True, - "allow_subject_alt_names_passthrough": True, - }, - "passthrough_extensions": { - "known_extensions": [1], - "additional_extensions": {}, - }, - }, - "publishing_options": { - "publish_ca_cert": True, - "publish_crl": True, - "encoding_format": 1, - }, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCaPoolRequest.meta.fields["ca_pool"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ca_pool"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ca_pool"][field])): - del request_init["ca_pool"][field][i][subfield] - else: - del request_init["ca_pool"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_ca_pool(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_ca_pool_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_ca_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_ca_pool] = mock_rpc - - request = {} - client.update_ca_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_ca_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_ca_pool_rest_required_fields(request_type=service.UpdateCaPoolRequest): - transport_class = transports.CertificateAuthorityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_ca_pool._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_ca_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation(name="operations/spam") @@ -20509,89 +15860,6 @@ def test_update_ca_pool_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_ca_pool_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "post_update_ca_pool" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_update_ca_pool" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCaPoolRequest.pb(service.UpdateCaPoolRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.UpdateCaPoolRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_ca_pool( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_ca_pool_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCaPoolRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/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.update_ca_pool(request) - - def test_update_ca_pool_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20651,54 +15919,6 @@ def test_update_ca_pool_rest_flattened_error(transport: str = "rest"): ) -def test_update_ca_pool_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCaPoolRequest, - dict, - ], -) -def test_get_ca_pool_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = resources.CaPool( - name="name_value", - tier=resources.CaPool.Tier.ENTERPRISE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CaPool.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_ca_pool(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CaPool) - assert response.name == "name_value" - assert response.tier == resources.CaPool.Tier.ENTERPRISE - - def test_get_ca_pool_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -20816,83 +16036,6 @@ def test_get_ca_pool_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_ca_pool_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_get_ca_pool" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_get_ca_pool" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCaPoolRequest.pb(service.GetCaPoolRequest()) - 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 = resources.CaPool.to_json(resources.CaPool()) - - request = service.GetCaPoolRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CaPool() - - client.get_ca_pool( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_ca_pool_rest_bad_request( - transport: str = "rest", request_type=service.GetCaPoolRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/caPools/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.get_ca_pool(request) - - def test_get_ca_pool_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20949,54 +16092,6 @@ def test_get_ca_pool_rest_flattened_error(transport: str = "rest"): ) -def test_get_ca_pool_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCaPoolsRequest, - dict, - ], -) -def test_list_ca_pools_rest(request_type): - client = CertificateAuthorityServiceClient( - 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 = service.ListCaPoolsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCaPoolsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_ca_pools(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCaPoolsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_ca_pools_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -21133,89 +16228,10 @@ def test_list_ca_pools_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_ca_pools_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_list_ca_pools_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_list_ca_pools" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_list_ca_pools" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCaPoolsRequest.pb(service.ListCaPoolsRequest()) - 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 = service.ListCaPoolsResponse.to_json( - service.ListCaPoolsResponse() - ) - - request = service.ListCaPoolsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCaPoolsResponse() - - client.list_ca_pools( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_ca_pools_rest_bad_request( - transport: str = "rest", request_type=service.ListCaPoolsRequest -): - client = CertificateAuthorityServiceClient( - 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.list_ca_pools(request) - - -def test_list_ca_pools_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -21329,41 +16345,6 @@ def test_list_ca_pools_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.DeleteCaPoolRequest, - dict, - ], -) -def test_delete_ca_pool_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_ca_pool(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_ca_pool_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -21497,87 +16478,6 @@ def test_delete_ca_pool_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_ca_pool_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "post_delete_ca_pool" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_delete_ca_pool" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteCaPoolRequest.pb(service.DeleteCaPoolRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.DeleteCaPoolRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_ca_pool( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_ca_pool_rest_bad_request( - transport: str = "rest", request_type=service.DeleteCaPoolRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/caPools/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.delete_ca_pool(request) - - def test_delete_ca_pool_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21632,49 +16532,6 @@ def test_delete_ca_pool_rest_flattened_error(transport: str = "rest"): ) -def test_delete_ca_pool_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.FetchCaCertsRequest, - dict, - ], -) -def test_fetch_ca_certs_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/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 = service.FetchCaCertsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.FetchCaCertsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.fetch_ca_certs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.FetchCaCertsResponse) - - def test_fetch_ca_certs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -21793,95 +16650,16 @@ def test_fetch_ca_certs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("caPool",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_ca_certs_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_fetch_ca_certs_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_fetch_ca_certs" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_fetch_ca_certs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.FetchCaCertsRequest.pb(service.FetchCaCertsRequest()) - 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 = service.FetchCaCertsResponse.to_json( - service.FetchCaCertsResponse() - ) - - request = service.FetchCaCertsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.FetchCaCertsResponse() - - client.fetch_ca_certs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_ca_certs_rest_bad_request( - transport: str = "rest", request_type=service.FetchCaCertsRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/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.fetch_ca_certs(request) - - -def test_fetch_ca_certs_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = service.FetchCaCertsResponse() + # 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 = service.FetchCaCertsResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -21931,64 +16709,6 @@ def test_fetch_ca_certs_rest_flattened_error(transport: str = "rest"): ) -def test_fetch_ca_certs_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCertificateRevocationListRequest, - dict, - ], -) -def test_get_certificate_revocation_list_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" - } - 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 = resources.CertificateRevocationList( - name="name_value", - sequence_number=1601, - pem_crl="pem_crl_value", - access_url="access_url_value", - state=resources.CertificateRevocationList.State.ACTIVE, - revision_id="revision_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CertificateRevocationList.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate_revocation_list(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CertificateRevocationList) - assert response.name == "name_value" - assert response.sequence_number == 1601 - assert response.pem_crl == "pem_crl_value" - assert response.access_url == "access_url_value" - assert response.state == resources.CertificateRevocationList.State.ACTIVE - assert response.revision_id == "revision_id_value" - - def test_get_certificate_revocation_list_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -22115,91 +16835,6 @@ def test_get_certificate_revocation_list_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_get_certificate_revocation_list", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_get_certificate_revocation_list", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCertificateRevocationListRequest.pb( - service.GetCertificateRevocationListRequest() - ) - 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 = resources.CertificateRevocationList.to_json( - resources.CertificateRevocationList() - ) - - request = service.GetCertificateRevocationListRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CertificateRevocationList() - - client.get_certificate_revocation_list( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_certificate_revocation_list_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateRevocationListRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" - } - 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_certificate_revocation_list(request) - - def test_get_certificate_revocation_list_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22259,56 +16894,6 @@ def test_get_certificate_revocation_list_rest_flattened_error(transport: str = " ) -def test_get_certificate_revocation_list_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificateRevocationListsRequest, - dict, - ], -) -def test_list_certificate_revocation_lists_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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 = service.ListCertificateRevocationListsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificateRevocationListsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_certificate_revocation_lists(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificateRevocationListsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_certificate_revocation_lists_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -22456,97 +17041,10 @@ def test_list_certificate_revocation_lists_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_list_certificate_revocation_lists_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_list_certificate_revocation_lists", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_list_certificate_revocation_lists", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCertificateRevocationListsRequest.pb( - service.ListCertificateRevocationListsRequest() - ) - 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 = ( - service.ListCertificateRevocationListsResponse.to_json( - service.ListCertificateRevocationListsResponse() - ) - ) - - request = service.ListCertificateRevocationListsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCertificateRevocationListsResponse() - - client.list_certificate_revocation_lists( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_certificate_revocation_lists_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificateRevocationListsRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" - } - 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.list_certificate_revocation_lists(request) - - -def test_list_certificate_revocation_lists_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -22671,136 +17169,6 @@ def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCertificateRevocationListRequest, - dict, - ], -) -def test_update_certificate_revocation_list_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_revocation_list": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" - } - } - request_init["certificate_revocation_list"] = { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5", - "sequence_number": 1601, - "revoked_certificates": [ - { - "certificate": "certificate_value", - "hex_serial_number": "hex_serial_number_value", - "revocation_reason": 1, - } - ], - "pem_crl": "pem_crl_value", - "access_url": "access_url_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "revision_id": "revision_id_value", - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateRevocationListRequest.meta.fields[ - "certificate_revocation_list" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_revocation_list" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["certificate_revocation_list"][field]) - ): - del request_init["certificate_revocation_list"][field][i][subfield] - else: - del request_init["certificate_revocation_list"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate_revocation_list(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_certificate_revocation_list_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -22944,121 +17312,32 @@ def test_update_certificate_revocation_list_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_update_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_update_certificate_revocation_list", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_update_certificate_revocation_list", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCertificateRevocationListRequest.pb( - service.UpdateCertificateRevocationListRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - - request = service.UpdateCertificateRevocationListRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_certificate_revocation_list( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_certificate_revocation_list_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateRevocationListRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_revocation_list": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" - } - } - 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_certificate_revocation_list(request) - - -def test_update_certificate_revocation_list_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "certificate_revocation_list": { - "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" - } - } - - # get truthy value for each flattened field - mock_args = dict( - certificate_revocation_list=resources.CertificateRevocationList( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -23100,199 +17379,6 @@ def test_update_certificate_revocation_list_rest_flattened_error( ) -def test_update_certificate_revocation_list_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCertificateTemplateRequest, - dict, - ], -) -def test_create_certificate_template_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["certificate_template"] = { - "name": "name_value", - "maximum_lifetime": {"seconds": 751, "nanos": 543}, - "predefined_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": [ - {"object_id": {}, "critical": True, "value": b"value_blob"} - ], - }, - "identity_constraints": { - "cel_expression": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - "allow_subject_passthrough": True, - "allow_subject_alt_names_passthrough": True, - }, - "passthrough_extensions": { - "known_extensions": [1], - "additional_extensions": {}, - }, - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCertificateTemplateRequest.meta.fields[ - "certificate_template" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_template" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_template"][field])): - del request_init["certificate_template"][field][i][subfield] - else: - del request_init["certificate_template"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_certificate_template(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_certificate_template_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -23456,91 +17542,6 @@ def test_create_certificate_template_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_certificate_template_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_create_certificate_template", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_create_certificate_template", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCertificateTemplateRequest.pb( - service.CreateCertificateTemplateRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.CreateCertificateTemplateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_certificate_template( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_certificate_template_rest_bad_request( - transport: str = "rest", request_type=service.CreateCertificateTemplateRequest -): - client = CertificateAuthorityServiceClient( - 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.create_certificate_template(request) - - def test_create_certificate_template_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23600,49 +17601,6 @@ def test_create_certificate_template_rest_flattened_error(transport: str = "rest ) -def test_create_certificate_template_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.DeleteCertificateTemplateRequest, - dict, - ], -) -def test_delete_certificate_template_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateTemplates/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_certificate_template(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_certificate_template_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -23770,93 +17728,6 @@ def test_delete_certificate_template_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_certificate_template_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_delete_certificate_template", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_delete_certificate_template", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteCertificateTemplateRequest.pb( - service.DeleteCertificateTemplateRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.DeleteCertificateTemplateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_certificate_template( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_certificate_template_rest_bad_request( - transport: str = "rest", request_type=service.DeleteCertificateTemplateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateTemplates/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.delete_certificate_template(request) - - def test_delete_certificate_template_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23914,56 +17785,6 @@ def test_delete_certificate_template_rest_flattened_error(transport: str = "rest ) -def test_delete_certificate_template_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCertificateTemplateRequest, - dict, - ], -) -def test_get_certificate_template_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateTemplates/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 = resources.CertificateTemplate( - name="name_value", - description="description_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CertificateTemplate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate_template(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CertificateTemplate) - assert response.name == "name_value" - assert response.description == "description_value" - - def test_get_certificate_template_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -24088,93 +17909,8 @@ def test_get_certificate_template_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_template_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_get_certificate_template", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_get_certificate_template", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCertificateTemplateRequest.pb( - service.GetCertificateTemplateRequest() - ) - 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 = resources.CertificateTemplate.to_json( - resources.CertificateTemplate() - ) - - request = service.GetCertificateTemplateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CertificateTemplate() - - client.get_certificate_template( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_certificate_template_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateTemplateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateTemplates/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.get_certificate_template(request) - - -def test_get_certificate_template_rest_flattened(): - client = CertificateAuthorityServiceClient( +def test_get_certificate_template_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -24232,54 +17968,6 @@ def test_get_certificate_template_rest_flattened_error(transport: str = "rest"): ) -def test_get_certificate_template_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificateTemplatesRequest, - dict, - ], -) -def test_list_certificate_templates_rest(request_type): - client = CertificateAuthorityServiceClient( - 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 = service.ListCertificateTemplatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificateTemplatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_certificate_templates(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificateTemplatesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_certificate_templates_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -24423,89 +18111,6 @@ def test_list_certificate_templates_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificate_templates_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_list_certificate_templates", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_list_certificate_templates", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCertificateTemplatesRequest.pb( - service.ListCertificateTemplatesRequest() - ) - 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 = service.ListCertificateTemplatesResponse.to_json( - service.ListCertificateTemplatesResponse() - ) - - request = service.ListCertificateTemplatesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCertificateTemplatesResponse() - - client.list_certificate_templates( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_certificate_templates_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificateTemplatesRequest -): - client = CertificateAuthorityServiceClient( - 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.list_certificate_templates(request) - - def test_list_certificate_templates_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24626,205 +18231,14 @@ def test_list_certificate_templates_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCertificateTemplateRequest, - dict, - ], -) -def test_update_certificate_template_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_template": { - "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" - } - } - request_init["certificate_template"] = { - "name": "projects/sample1/locations/sample2/certificateTemplates/sample3", - "maximum_lifetime": {"seconds": 751, "nanos": 543}, - "predefined_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], - }, - "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, - "policy_ids": {}, - "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], - "name_constraints": { - "critical": True, - "permitted_dns_names": [ - "permitted_dns_names_value1", - "permitted_dns_names_value2", - ], - "excluded_dns_names": [ - "excluded_dns_names_value1", - "excluded_dns_names_value2", - ], - "permitted_ip_ranges": [ - "permitted_ip_ranges_value1", - "permitted_ip_ranges_value2", - ], - "excluded_ip_ranges": [ - "excluded_ip_ranges_value1", - "excluded_ip_ranges_value2", - ], - "permitted_email_addresses": [ - "permitted_email_addresses_value1", - "permitted_email_addresses_value2", - ], - "excluded_email_addresses": [ - "excluded_email_addresses_value1", - "excluded_email_addresses_value2", - ], - "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], - "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], - }, - "additional_extensions": [ - {"object_id": {}, "critical": True, "value": b"value_blob"} - ], - }, - "identity_constraints": { - "cel_expression": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - "allow_subject_passthrough": True, - "allow_subject_alt_names_passthrough": True, - }, - "passthrough_extensions": { - "known_extensions": [1], - "additional_extensions": {}, - }, - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateTemplateRequest.meta.fields[ - "certificate_template" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_template" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_template"][field])): - del request_init["certificate_template"][field][i][subfield] - else: - del request_init["certificate_template"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate_template(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_certificate_template_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_certificate_template_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -24958,95 +18372,6 @@ def test_update_certificate_template_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_template_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_update_certificate_template", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_update_certificate_template", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCertificateTemplateRequest.pb( - service.UpdateCertificateTemplateRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = service.UpdateCertificateTemplateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_certificate_template( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_certificate_template_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateTemplateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_template": { - "name": "projects/sample1/locations/sample2/certificateTemplates/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.update_certificate_template(request) - - def test_update_certificate_template_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -25108,12 +18433,6 @@ def test_update_certificate_template_rest_flattened_error(transport: str = "rest ) -def test_update_certificate_template_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CertificateAuthorityServiceGrpcTransport( @@ -25206,1443 +18525,8763 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = CertificateAuthorityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.CertificateAuthorityServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.create_certificate(request=None) -def test_certificate_authority_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() + assert args[0] == request_msg -def test_certificate_authority_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_certificate", - "get_certificate", - "list_certificates", - "revoke_certificate", - "update_certificate", - "activate_certificate_authority", - "create_certificate_authority", - "disable_certificate_authority", - "enable_certificate_authority", - "fetch_certificate_authority_csr", - "get_certificate_authority", - "list_certificate_authorities", - "undelete_certificate_authority", - "delete_certificate_authority", - "update_certificate_authority", - "create_ca_pool", - "update_ca_pool", - "get_ca_pool", - "list_ca_pools", - "delete_ca_pool", - "fetch_ca_certs", - "get_certificate_revocation_list", - "list_certificate_revocation_lists", - "update_certificate_revocation_list", - "create_certificate_template", - "delete_certificate_template", - "get_certificate_template", - "list_certificate_templates", - "update_certificate_template", - "set_iam_policy", - "get_iam_policy", - "test_iam_permissions", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + call.return_value = resources.Certificate() + client.get_certificate(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_certificate_authority_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificates_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CertificateAuthorityServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + type(client.transport.list_certificates), "__call__" + ) as call: + call.return_value = service.ListCertificatesResponse() + client.list_certificates(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() -def test_certificate_authority_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CertificateAuthorityServiceTransport() - adc.assert_called_once() + assert args[0] == request_msg -def test_certificate_authority_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CertificateAuthorityServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.revoke_certificate(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - transports.CertificateAuthorityServiceRestTransport, - ], -) -def test_certificate_authority_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CertificateAuthorityServiceGrpcTransport, grpc_helpers), - ( - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - grpc_helpers_async, - ), - ], -) -def test_certificate_authority_service_transport_create_channel( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + type(client.transport.update_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.update_certificate(request=None) - create_channel.assert_called_with( - "privateca.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="privateca.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_activate_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.activate_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() -def test_certificate_authority_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.CertificateAuthorityServiceRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_certificate_authority_service_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_authority_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_certificate_authority(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_certificate_authority_service_host_no_port(transport_name): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_disable_certificate_authority_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privateca.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "privateca.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://privateca.googleapis.com" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_certificate_authority_service_host_with_port(transport_name): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enable_certificate_authority_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privateca.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "privateca.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://privateca.googleapis.com:8000" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.enable_certificate_authority(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_certificate_authority_service_client_transport_session_collision( - transport_name, -): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CertificateAuthorityServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CertificateAuthorityServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_certificate._session - session2 = client2.transport.create_certificate._session - assert session1 != session2 - session1 = client1.transport.get_certificate._session - session2 = client2.transport.get_certificate._session - assert session1 != session2 - session1 = client1.transport.list_certificates._session - session2 = client2.transport.list_certificates._session - assert session1 != session2 - session1 = client1.transport.revoke_certificate._session - session2 = client2.transport.revoke_certificate._session - assert session1 != session2 - session1 = client1.transport.update_certificate._session - session2 = client2.transport.update_certificate._session - assert session1 != session2 - session1 = client1.transport.activate_certificate_authority._session - session2 = client2.transport.activate_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.create_certificate_authority._session - session2 = client2.transport.create_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.disable_certificate_authority._session - session2 = client2.transport.disable_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.enable_certificate_authority._session - session2 = client2.transport.enable_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.fetch_certificate_authority_csr._session - session2 = client2.transport.fetch_certificate_authority_csr._session - assert session1 != session2 - session1 = client1.transport.get_certificate_authority._session - session2 = client2.transport.get_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.list_certificate_authorities._session - session2 = client2.transport.list_certificate_authorities._session - assert session1 != session2 - session1 = client1.transport.undelete_certificate_authority._session - session2 = client2.transport.undelete_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.delete_certificate_authority._session - session2 = client2.transport.delete_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.update_certificate_authority._session - session2 = client2.transport.update_certificate_authority._session - assert session1 != session2 - session1 = client1.transport.create_ca_pool._session - session2 = client2.transport.create_ca_pool._session - assert session1 != session2 - session1 = client1.transport.update_ca_pool._session - session2 = client2.transport.update_ca_pool._session - assert session1 != session2 - session1 = client1.transport.get_ca_pool._session - session2 = client2.transport.get_ca_pool._session - assert session1 != session2 - session1 = client1.transport.list_ca_pools._session - session2 = client2.transport.list_ca_pools._session - assert session1 != session2 - session1 = client1.transport.delete_ca_pool._session - session2 = client2.transport.delete_ca_pool._session - assert session1 != session2 - session1 = client1.transport.fetch_ca_certs._session - session2 = client2.transport.fetch_ca_certs._session - assert session1 != session2 - session1 = client1.transport.get_certificate_revocation_list._session - session2 = client2.transport.get_certificate_revocation_list._session - assert session1 != session2 - session1 = client1.transport.list_certificate_revocation_lists._session - session2 = client2.transport.list_certificate_revocation_lists._session - assert session1 != session2 - session1 = client1.transport.update_certificate_revocation_list._session - session2 = client2.transport.update_certificate_revocation_list._session - assert session1 != session2 - session1 = client1.transport.create_certificate_template._session - session2 = client2.transport.create_certificate_template._session - assert session1 != session2 - session1 = client1.transport.delete_certificate_template._session - session2 = client2.transport.delete_certificate_template._session - assert session1 != session2 - session1 = client1.transport.get_certificate_template._session - session2 = client2.transport.get_certificate_template._session - assert session1 != session2 - session1 = client1.transport.list_certificate_templates._session - session2 = client2.transport.list_certificate_templates._session - assert session1 != session2 - session1 = client1.transport.update_certificate_template._session - session2 = client2.transport.update_certificate_template._session - assert session1 != session2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() + assert args[0] == request_msg -def test_certificate_authority_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.CertificateAuthorityServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_certificate_authority_csr_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + call.return_value = service.FetchCertificateAuthorityCsrResponse() + client.fetch_certificate_authority_csr(request=None) -def test_certificate_authority_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() - # Check that channel is used if provided. - transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + call.return_value = resources.CertificateAuthority() + client.get_certificate_authority(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + assert args[0] == request_msg - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_authorities_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + call.return_value = service.ListCertificateAuthoritiesResponse() + client.list_certificate_authorities(request=None) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + assert args[0] == request_msg -def test_certificate_authority_service_grpc_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_certificate_authority_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.undelete_certificate_authority(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UndeleteCertificateAuthorityRequest() + assert args[0] == request_msg -def test_certificate_authority_service_grpc_lro_async_client(): - client = CertificateAuthorityServiceAsyncClient( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_certificate_authority(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateAuthorityRequest() + assert args[0] == request_msg -def test_ca_pool_path(): - project = "squid" - location = "clam" - ca_pool = "whelk" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}".format( - project=project, - location=location, - ca_pool=ca_pool, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = CertificateAuthorityServiceClient.ca_pool_path(project, location, ca_pool) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_certificate_authority(request=None) -def test_parse_ca_pool_path(): - expected = { - "project": "octopus", - "location": "oyster", - "ca_pool": "nudibranch", - } - path = CertificateAuthorityServiceClient.ca_pool_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_ca_pool_path(path) - assert expected == actual + assert args[0] == request_msg -def test_certificate_path(): - project = "cuttlefish" - location = "mussel" - ca_pool = "winkle" - certificate = "nautilus" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificates/{certificate}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate=certificate, - ) - actual = CertificateAuthorityServiceClient.certificate_path( - project, location, ca_pool, certificate +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ca_pool_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_ca_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_ca_pool(request=None) -def test_parse_certificate_path(): - expected = { - "project": "scallop", - "location": "abalone", - "ca_pool": "squid", - "certificate": "clam", - } - path = CertificateAuthorityServiceClient.certificate_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCaPoolRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_path(path) - assert expected == actual + assert args[0] == request_msg -def test_certificate_authority_path(): - project = "whelk" - location = "octopus" - ca_pool = "oyster" - certificate_authority = "nudibranch" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate_authority=certificate_authority, - ) - actual = CertificateAuthorityServiceClient.certificate_authority_path( - project, location, ca_pool, certificate_authority +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ca_pool_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_ca_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_ca_pool(request=None) -def test_parse_certificate_authority_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "ca_pool": "winkle", - "certificate_authority": "nautilus", - } - path = CertificateAuthorityServiceClient.certificate_authority_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCaPoolRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_authority_path(path) - assert expected == actual + assert args[0] == request_msg -def test_certificate_revocation_list_path(): - project = "scallop" - location = "abalone" - ca_pool = "squid" - certificate_authority = "clam" - certificate_revocation_list = "whelk" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}/certificateRevocationLists/{certificate_revocation_list}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate_authority=certificate_authority, - certificate_revocation_list=certificate_revocation_list, - ) - actual = CertificateAuthorityServiceClient.certificate_revocation_list_path( - project, location, ca_pool, certificate_authority, certificate_revocation_list +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ca_pool_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: + call.return_value = resources.CaPool() + client.get_ca_pool(request=None) -def test_parse_certificate_revocation_list_path(): - expected = { - "project": "octopus", - "location": "oyster", - "ca_pool": "nudibranch", - "certificate_authority": "cuttlefish", - "certificate_revocation_list": "mussel", - } - path = CertificateAuthorityServiceClient.certificate_revocation_list_path( - **expected - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCaPoolRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_revocation_list_path( - path - ) - assert expected == actual + assert args[0] == request_msg -def test_certificate_template_path(): - project = "winkle" - location = "nautilus" - certificate_template = "scallop" - expected = "projects/{project}/locations/{location}/certificateTemplates/{certificate_template}".format( - project=project, - location=location, - certificate_template=certificate_template, - ) - actual = CertificateAuthorityServiceClient.certificate_template_path( - project, location, certificate_template +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_ca_pools_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_ca_pools), "__call__") as call: + call.return_value = service.ListCaPoolsResponse() + client.list_ca_pools(request=None) -def test_parse_certificate_template_path(): - expected = { - "project": "abalone", - "location": "squid", - "certificate_template": "clam", - } - path = CertificateAuthorityServiceClient.certificate_template_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCaPoolsRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_template_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = CertificateAuthorityServiceClient.common_billing_account_path( - billing_account +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_ca_pool_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_ca_pool), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_ca_pool(request=None) -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CertificateAuthorityServiceClient.common_billing_account_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCaPoolRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_billing_account_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_ca_certs_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = CertificateAuthorityServiceClient.common_folder_path(folder) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_ca_certs), "__call__") as call: + call.return_value = service.FetchCaCertsResponse() + client.fetch_ca_certs(request=None) -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CertificateAuthorityServiceClient.common_folder_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCaCertsRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_folder_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_revocation_list_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = CertificateAuthorityServiceClient.common_organization_path(organization) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + call.return_value = resources.CertificateRevocationList() + client.get_certificate_revocation_list(request=None) -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CertificateAuthorityServiceClient.common_organization_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_organization_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_revocation_lists_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = CertificateAuthorityServiceClient.common_project_path(project) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + call.return_value = service.ListCertificateRevocationListsResponse() + client.list_certificate_revocation_lists(request=None) -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CertificateAuthorityServiceClient.common_project_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_project_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_revocation_list_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - actual = CertificateAuthorityServiceClient.common_location_path(project, location) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_certificate_revocation_list(request=None) -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CertificateAuthorityServiceClient.common_location_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_location_path(path) - assert expected == actual + assert args[0] == request_msg -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_template_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. with mock.patch.object( - transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + type(client.transport.create_certificate_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_certificate_template(request=None) - with mock.patch.object( - transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = CertificateAuthorityServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateTemplateRequest() + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CertificateAuthorityServiceAsyncClient( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_certificate_template_empty_call_grpc(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="grpc", ) + + # Mock the actual call, and fake the request. with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + type(client.transport.delete_certificate_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateTemplateRequest() + assert args[0] == request_msg -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest -): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_template_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_template), "__call__" + ) as call: + call.return_value = resources.CertificateTemplate() + client.get_certificate_template(request=None) - # 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_location(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateTemplateRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.GetLocationRequest, - dict, - ], -) -def test_get_location_rest(request_type): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_templates_empty_call_grpc(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request_init = {"name": "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 = locations_pb2.Location() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_templates), "__call__" + ) as call: + call.return_value = service.ListCertificateTemplatesResponse() + client.list_certificate_templates(request=None) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateTemplatesRequest() - response = client.get_location(request) + assert args[0] == request_msg - # Establish that the response is the type that we expect. + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_template_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateTemplateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CertificateAuthorityServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.create_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.get_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificates_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_certificates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_revoke_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.revoke_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.update_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_activate_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.activate_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_disable_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.disable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_enable_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.enable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_certificate_authority_csr_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", + ) + ) + await client.fetch_certificate_authority_csr(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CaPool.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) + ) + await client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificate_authorities_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_certificate_authorities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_undelete_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.undelete_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UndeleteCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_ca_pool_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_ca_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_ca_pool_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_ca_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_ca_pool_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CaPool( + name="name_value", + tier=resources.CaPool.Tier.ENTERPRISE, + ) + ) + await client.get_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_ca_pools_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_ca_pools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCaPoolsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_ca_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCaPoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_ca_pool_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_ca_pool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_ca_certs_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_ca_certs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.FetchCaCertsResponse() + ) + await client.fetch_ca_certs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCaCertsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_revocation_list_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + revision_id="revision_id_value", + ) + ) + await client.get_certificate_revocation_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificate_revocation_lists_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_certificate_revocation_lists(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_revocation_list_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_certificate_revocation_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_certificate_template_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_certificate_template_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_certificate_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_template_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CertificateTemplate( + name="name_value", + description="description_value", + ) + ) + await client.get_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificate_templates_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificateTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_certificate_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateTemplatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_template_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateTemplateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CertificateAuthorityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_certificate_rest_bad_request( + request_type=service.CreateCertificateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_certificate(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateRequest, + dict, + ], +) +def test_create_certificate_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + "subject_key_id": {"key_id": "key_id_value"}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCertificateRequest.meta.fields["certificate"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["certificate"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate"][field])): + del request_init["certificate"][field][i][subfield] + else: + del request_init["certificate"][field][subfield] + 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 = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateRequest.pb( + service.CreateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value + + request = service.CreateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.create_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_rest_bad_request(request_type=service.GetCertificateRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateRequest, + dict, + ], +) +def test_get_certificate_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + 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 = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value + + request = service.GetCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.get_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificates_rest_bad_request( + request_type=service.ListCertificatesRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_certificates(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificatesRequest, + dict, + ], +) +def test_list_certificates_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificatesRequest.pb( + service.ListCertificatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificatesResponse.to_json( + service.ListCertificatesResponse() + ) + req.return_value.content = return_value + + request = service.ListCertificatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificatesResponse() + + client.list_certificates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_revoke_certificate_rest_bad_request( + request_type=service.RevokeCertificateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.revoke_certificate(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.RevokeCertificateRequest, + dict, + ], +) +def test_revoke_certificate_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + 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 = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.revoke_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_revoke_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RevokeCertificateRequest.pb( + service.RevokeCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value + + request = service.RevokeCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.revoke_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_rest_bad_request( + request_type=service.UpdateCertificateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRequest, + dict, + ], +) +def test_update_certificate_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + "subject_key_id": {"key_id": "key_id_value"}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateRequest.meta.fields["certificate"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["certificate"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate"][field])): + del request_init["certificate"][field][i][subfield] + else: + del request_init["certificate"][field][subfield] + 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 = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRequest.pb( + service.UpdateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value + + request = service.UpdateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.update_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_activate_certificate_authority_rest_bad_request( + request_type=service.ActivateCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.activate_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ActivateCertificateAuthorityRequest, + dict, + ], +) +def test_activate_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.activate_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_activate_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_activate_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_activate_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ActivateCertificateAuthorityRequest.pb( + service.ActivateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.ActivateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.activate_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_authority_rest_bad_request( + request_type=service.CreateCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateAuthorityRequest, + dict, + ], +) +def test_create_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + "subject_key_id": {"key_id": "key_id_value"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCertificateAuthorityRequest.meta.fields[ + "certificate_authority" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_authority" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_authority"][field])): + del request_init["certificate_authority"][field][i][subfield] + else: + del request_init["certificate_authority"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_create_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_create_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateAuthorityRequest.pb( + service.CreateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_disable_certificate_authority_rest_bad_request( + request_type=service.DisableCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.disable_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DisableCertificateAuthorityRequest, + dict, + ], +) +def test_disable_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.disable_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_disable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_disable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DisableCertificateAuthorityRequest.pb( + service.DisableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DisableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.disable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enable_certificate_authority_rest_bad_request( + request_type=service.EnableCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.enable_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.EnableCertificateAuthorityRequest, + dict, + ], +) +def test_enable_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enable_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_enable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_enable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.EnableCertificateAuthorityRequest.pb( + service.EnableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.EnableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_certificate_authority_csr_rest_bad_request( + request_type=service.FetchCertificateAuthorityCsrRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.fetch_certificate_authority_csr(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCertificateAuthorityCsrRequest, + dict, + ], +) +def test_fetch_certificate_authority_csr_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_certificate_authority_csr(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) + assert response.pem_csr == "pem_csr_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_fetch_certificate_authority_csr", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_fetch_certificate_authority_csr", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCertificateAuthorityCsrRequest.pb( + service.FetchCertificateAuthorityCsrRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.FetchCertificateAuthorityCsrResponse.to_json( + service.FetchCertificateAuthorityCsrResponse() + ) + req.return_value.content = return_value + + request = service.FetchCertificateAuthorityCsrRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCertificateAuthorityCsrResponse() + + client.fetch_certificate_authority_csr( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_authority_rest_bad_request( + request_type=service.GetCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateAuthorityRequest, + dict, + ], +) +def test_get_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CaPool.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateAuthority) + assert response.name == "name_value" + assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED + assert response.tier == resources.CaPool.Tier.ENTERPRISE + assert response.state == resources.CertificateAuthority.State.ENABLED + assert response.pem_ca_certificates == ["pem_ca_certificates_value"] + assert response.gcs_bucket == "gcs_bucket_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateAuthorityRequest.pb( + service.GetCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CertificateAuthority.to_json( + resources.CertificateAuthority() + ) + req.return_value.content = return_value + + request = service.GetCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateAuthority() + + client.get_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_authorities_rest_bad_request( + request_type=service.ListCertificateAuthoritiesRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_certificate_authorities(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateAuthoritiesRequest, + dict, + ], +) +def test_list_certificate_authorities_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/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 = service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_authorities(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateAuthoritiesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_authorities_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_authorities", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_authorities", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateAuthoritiesRequest.pb( + service.ListCertificateAuthoritiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificateAuthoritiesResponse.to_json( + service.ListCertificateAuthoritiesResponse() + ) + req.return_value.content = return_value + + request = service.ListCertificateAuthoritiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateAuthoritiesResponse() + + client.list_certificate_authorities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_certificate_authority_rest_bad_request( + request_type=service.UndeleteCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.undelete_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UndeleteCertificateAuthorityRequest, + dict, + ], +) +def test_undelete_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.undelete_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_undelete_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_undelete_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UndeleteCertificateAuthorityRequest.pb( + service.UndeleteCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UndeleteCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_authority_rest_bad_request( + request_type=service.DeleteCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCertificateAuthorityRequest, + dict, + ], +) +def test_delete_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_delete_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_delete_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCertificateAuthorityRequest.pb( + service.DeleteCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_authority_rest_bad_request( + request_type=service.UpdateCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateAuthorityRequest, + dict, + ], +) +def test_update_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + "subject_key_id": {"key_id": "key_id_value"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateAuthorityRequest.meta.fields[ + "certificate_authority" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_authority" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_authority"][field])): + del request_init["certificate_authority"][field][i][subfield] + else: + del request_init["certificate_authority"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateAuthorityRequest.pb( + service.UpdateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_ca_pool_rest_bad_request(request_type=service.CreateCaPoolRequest): + client = CertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_ca_pool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCaPoolRequest, + dict, + ], +) +def test_create_ca_pool_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["ca_pool"] = { + "name": "name_value", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": { + "publish_ca_cert": True, + "publish_crl": True, + "encoding_format": 1, + }, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCaPoolRequest.meta.fields["ca_pool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ca_pool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ca_pool"][field])): + del request_init["ca_pool"][field][i][subfield] + else: + del request_init["ca_pool"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_ca_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_create_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCaPoolRequest.pb(service.CreateCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_ca_pool_rest_bad_request(request_type=service.UpdateCaPoolRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_ca_pool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCaPoolRequest, + dict, + ], +) +def test_update_ca_pool_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/sample3"} + } + request_init["ca_pool"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": { + "publish_ca_cert": True, + "publish_crl": True, + "encoding_format": 1, + }, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCaPoolRequest.meta.fields["ca_pool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ca_pool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ca_pool"][field])): + del request_init["ca_pool"][field][i][subfield] + else: + del request_init["ca_pool"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_ca_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_update_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCaPoolRequest.pb(service.UpdateCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ca_pool_rest_bad_request(request_type=service.GetCaPoolRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_ca_pool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCaPoolRequest, + dict, + ], +) +def test_get_ca_pool_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = resources.CaPool( + name="name_value", + tier=resources.CaPool.Tier.ENTERPRISE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CaPool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_ca_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CaPool) + assert response.name == "name_value" + assert response.tier == resources.CaPool.Tier.ENTERPRISE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_get_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCaPoolRequest.pb(service.GetCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CaPool.to_json(resources.CaPool()) + req.return_value.content = return_value + + request = service.GetCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CaPool() + + client.get_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_ca_pools_rest_bad_request(request_type=service.ListCaPoolsRequest): + client = CertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_ca_pools(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCaPoolsRequest, + dict, + ], +) +def test_list_ca_pools_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + 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 = service.ListCaPoolsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCaPoolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_ca_pools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCaPoolsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_ca_pools_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_list_ca_pools" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_ca_pools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCaPoolsRequest.pb(service.ListCaPoolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCaPoolsResponse.to_json( + service.ListCaPoolsResponse() + ) + req.return_value.content = return_value + + request = service.ListCaPoolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCaPoolsResponse() + + client.list_ca_pools( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_ca_pool_rest_bad_request(request_type=service.DeleteCaPoolRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_ca_pool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCaPoolRequest, + dict, + ], +) +def test_delete_ca_pool_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_ca_pool(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_delete_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_delete_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCaPoolRequest.pb(service.DeleteCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_ca_certs_rest_bad_request(request_type=service.FetchCaCertsRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.fetch_ca_certs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCaCertsRequest, + dict, + ], +) +def test_fetch_ca_certs_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/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 = service.FetchCaCertsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.FetchCaCertsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_ca_certs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCaCertsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_ca_certs_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_fetch_ca_certs" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_fetch_ca_certs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCaCertsRequest.pb(service.FetchCaCertsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.FetchCaCertsResponse.to_json( + service.FetchCaCertsResponse() + ) + req.return_value.content = return_value + + request = service.FetchCaCertsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCaCertsResponse() + + client.fetch_ca_certs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_revocation_list_rest_bad_request( + request_type=service.GetCertificateRevocationListRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate_revocation_list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateRevocationListRequest, + dict, + ], +) +def test_get_certificate_revocation_list_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + 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 = resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + revision_id="revision_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateRevocationList) + assert response.name == "name_value" + assert response.sequence_number == 1601 + assert response.pem_crl == "pem_crl_value" + assert response.access_url == "access_url_value" + assert response.state == resources.CertificateRevocationList.State.ACTIVE + assert response.revision_id == "revision_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRevocationListRequest.pb( + service.GetCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CertificateRevocationList.to_json( + resources.CertificateRevocationList() + ) + req.return_value.content = return_value + + request = service.GetCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateRevocationList() + + client.get_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_revocation_lists_rest_bad_request( + request_type=service.ListCertificateRevocationListsRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_certificate_revocation_lists(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateRevocationListsRequest, + dict, + ], +) +def test_list_certificate_revocation_lists_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + 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 = service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCertificateRevocationListsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_revocation_lists(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateRevocationListsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_revocation_lists", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_revocation_lists", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateRevocationListsRequest.pb( + service.ListCertificateRevocationListsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificateRevocationListsResponse.to_json( + service.ListCertificateRevocationListsResponse() + ) + req.return_value.content = return_value + + request = service.ListCertificateRevocationListsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateRevocationListsResponse() + + client.list_certificate_revocation_lists( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_revocation_list_rest_bad_request( + request_type=service.UpdateCertificateRevocationListRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate_revocation_list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRevocationListRequest, + dict, + ], +) +def test_update_certificate_revocation_list_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + } + request_init["certificate_revocation_list"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5", + "sequence_number": 1601, + "revoked_certificates": [ + { + "certificate": "certificate_value", + "hex_serial_number": "hex_serial_number_value", + "revocation_reason": 1, + } + ], + "pem_crl": "pem_crl_value", + "access_url": "access_url_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "revision_id": "revision_id_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateRevocationListRequest.meta.fields[ + "certificate_revocation_list" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_revocation_list" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["certificate_revocation_list"][field]) + ): + del request_init["certificate_revocation_list"][field][i][subfield] + else: + del request_init["certificate_revocation_list"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRevocationListRequest.pb( + service.UpdateCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_template_rest_bad_request( + request_type=service.CreateCertificateTemplateRequest, +): + client = CertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_certificate_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateTemplateRequest, + dict, + ], +) +def test_create_certificate_template_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_template"] = { + "name": "name_value", + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCertificateTemplateRequest.meta.fields[ + "certificate_template" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_template" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_template"][field])): + del request_init["certificate_template"][field][i][subfield] + else: + del request_init["certificate_template"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_template(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_create_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_create_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateTemplateRequest.pb( + service.CreateCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_template_rest_bad_request( + request_type=service.DeleteCertificateTemplateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_certificate_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCertificateTemplateRequest, + dict, + ], +) +def test_delete_certificate_template_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_template(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_delete_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_delete_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCertificateTemplateRequest.pb( + service.DeleteCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_template_rest_bad_request( + request_type=service.GetCertificateTemplateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateTemplateRequest, + dict, + ], +) +def test_get_certificate_template_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/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 = resources.CertificateTemplate( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CertificateTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateTemplateRequest.pb( + service.GetCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CertificateTemplate.to_json( + resources.CertificateTemplate() + ) + req.return_value.content = return_value + + request = service.GetCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateTemplate() + + client.get_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_templates_rest_bad_request( + request_type=service.ListCertificateTemplatesRequest, +): + client = CertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_certificate_templates(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateTemplatesRequest, + dict, + ], +) +def test_list_certificate_templates_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + 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 = service.ListCertificateTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCertificateTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_templates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateTemplatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_templates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_templates", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_templates", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateTemplatesRequest.pb( + service.ListCertificateTemplatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificateTemplatesResponse.to_json( + service.ListCertificateTemplatesResponse() + ) + req.return_value.content = return_value + + request = service.ListCertificateTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateTemplatesResponse() + + client.list_certificate_templates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_template_rest_bad_request( + request_type=service.UpdateCertificateTemplateRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "certificate_template": { + "name": "projects/sample1/locations/sample2/certificateTemplates/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateTemplateRequest, + dict, + ], +) +def test_update_certificate_template_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_template": { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + } + request_init["certificate_template"] = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3", + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateTemplateRequest.meta.fields[ + "certificate_template" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_template" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_template"][field])): + del request_init["certificate_template"][field][i][subfield] + else: + del request_init["certificate_template"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_template(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateTemplateRequest.pb( + service.UpdateCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.Location) -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + client.create_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + client.get_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificates_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificates), "__call__" + ) as call: + client.list_certificates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + client.revoke_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate), "__call__" + ) as call: + client.update_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_activate_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + client.activate_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + client.create_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_disable_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + client.disable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enable_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + client.enable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_certificate_authority_csr_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + client.fetch_certificate_authority_csr(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_authorities_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + client.list_certificate_authorities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_certificate_authority), "__call__" + ) as call: + client.undelete_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UndeleteCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_certificate_authority), "__call__" + ) as call: + client.delete_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + client.update_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ca_pool_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_ca_pool), "__call__") as call: + client.create_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ca_pool_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_ca_pool), "__call__") as call: + client.update_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ca_pool_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_ca_pool), "__call__") as call: + client.get_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_ca_pools_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_ca_pools), "__call__") as call: + client.list_ca_pools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCaPoolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_ca_pool_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_ca_pool), "__call__") as call: + client.delete_ca_pool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCaPoolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_ca_certs_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_ca_certs), "__call__") as call: + client.fetch_ca_certs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCaCertsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_revocation_list_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + client.get_certificate_revocation_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_revocation_lists_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + client.list_certificate_revocation_lists(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_revocation_list_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + client.update_certificate_revocation_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_template_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_template), "__call__" + ) as call: + client.create_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_certificate_template_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_certificate_template), "__call__" + ) as call: + client.delete_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_template_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_template), "__call__" + ) as call: + client.get_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateTemplateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_templates_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_templates), "__call__" + ) as call: + client.list_certificate_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateTemplatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_template_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_template), "__call__" + ) as call: + client.update_certificate_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateTemplateRequest() + + assert args[0] == request_msg + + +def test_certificate_authority_service_rest_lro_client(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CertificateAuthorityServiceGrpcTransport, + ) + + +def test_certificate_authority_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_certificate_authority_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_certificate", + "get_certificate", + "list_certificates", + "revoke_certificate", + "update_certificate", + "activate_certificate_authority", + "create_certificate_authority", + "disable_certificate_authority", + "enable_certificate_authority", + "fetch_certificate_authority_csr", + "get_certificate_authority", + "list_certificate_authorities", + "undelete_certificate_authority", + "delete_certificate_authority", + "update_certificate_authority", + "create_ca_pool", + "update_ca_pool", + "get_ca_pool", + "list_ca_pools", + "delete_ca_pool", + "fetch_ca_certs", + "get_certificate_revocation_list", + "list_certificate_revocation_lists", + "update_certificate_revocation_list", + "create_certificate_template", + "delete_certificate_template", + "get_certificate_template", + "list_certificate_templates", + "update_certificate_template", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_certificate_authority_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.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CertificateAuthorityServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_certificate_authority_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CertificateAuthorityServiceTransport() + adc.assert_called_once() + + +def test_certificate_authority_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CertificateAuthorityServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, + ], +) +def test_certificate_authority_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CertificateAuthorityServiceGrpcTransport, grpc_helpers), + ( + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_certificate_authority_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "privateca.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="privateca.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_certificate_authority_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.CertificateAuthorityServiceRestTransport( + 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_certificate_authority_service_host_no_port(transport_name): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privateca.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_certificate_authority_service_host_with_port(transport_name): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privateca.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privateca.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_certificate_authority_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CertificateAuthorityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CertificateAuthorityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_certificate._session + session2 = client2.transport.create_certificate._session + assert session1 != session2 + session1 = client1.transport.get_certificate._session + session2 = client2.transport.get_certificate._session + assert session1 != session2 + session1 = client1.transport.list_certificates._session + session2 = client2.transport.list_certificates._session + assert session1 != session2 + session1 = client1.transport.revoke_certificate._session + session2 = client2.transport.revoke_certificate._session + assert session1 != session2 + session1 = client1.transport.update_certificate._session + session2 = client2.transport.update_certificate._session + assert session1 != session2 + session1 = client1.transport.activate_certificate_authority._session + session2 = client2.transport.activate_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.create_certificate_authority._session + session2 = client2.transport.create_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.disable_certificate_authority._session + session2 = client2.transport.disable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.enable_certificate_authority._session + session2 = client2.transport.enable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.fetch_certificate_authority_csr._session + session2 = client2.transport.fetch_certificate_authority_csr._session + assert session1 != session2 + session1 = client1.transport.get_certificate_authority._session + session2 = client2.transport.get_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.list_certificate_authorities._session + session2 = client2.transport.list_certificate_authorities._session + assert session1 != session2 + session1 = client1.transport.undelete_certificate_authority._session + session2 = client2.transport.undelete_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_authority._session + session2 = client2.transport.delete_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.update_certificate_authority._session + session2 = client2.transport.update_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.create_ca_pool._session + session2 = client2.transport.create_ca_pool._session + assert session1 != session2 + session1 = client1.transport.update_ca_pool._session + session2 = client2.transport.update_ca_pool._session + assert session1 != session2 + session1 = client1.transport.get_ca_pool._session + session2 = client2.transport.get_ca_pool._session + assert session1 != session2 + session1 = client1.transport.list_ca_pools._session + session2 = client2.transport.list_ca_pools._session + assert session1 != session2 + session1 = client1.transport.delete_ca_pool._session + session2 = client2.transport.delete_ca_pool._session + assert session1 != session2 + session1 = client1.transport.fetch_ca_certs._session + session2 = client2.transport.fetch_ca_certs._session + assert session1 != session2 + session1 = client1.transport.get_certificate_revocation_list._session + session2 = client2.transport.get_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.list_certificate_revocation_lists._session + session2 = client2.transport.list_certificate_revocation_lists._session + assert session1 != session2 + session1 = client1.transport.update_certificate_revocation_list._session + session2 = client2.transport.update_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.create_certificate_template._session + session2 = client2.transport.create_certificate_template._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_template._session + session2 = client2.transport.delete_certificate_template._session + assert session1 != session2 + session1 = client1.transport.get_certificate_template._session + session2 = client2.transport.get_certificate_template._session + assert session1 != session2 + session1 = client1.transport.list_certificate_templates._session + session2 = client2.transport.list_certificate_templates._session + assert session1 != session2 + session1 = client1.transport.update_certificate_template._session + session2 = client2.transport.update_certificate_template._session + assert session1 != session2 + + +def test_certificate_authority_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CertificateAuthorityServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - # 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.list_locations(request) +def test_certificate_authority_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "request_type", + "transport_class", [ - locations_pb2.ListLocationsRequest, - dict, + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, ], ) -def test_list_locations_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +def test_certificate_authority_service_transport_channel_mtls_with_client_cert_source( + transport_class, ): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request - ) + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel - # 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_iam_policy(request) + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "request_type", + "transport_class", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, ], ) -def test_get_iam_policy_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"resource": "projects/sample1/locations/sample2/caPools/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 = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_certificate_authority_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() - response = client.get_iam_policy(request) + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): +def test_certificate_authority_service_grpc_lro_client(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - # 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.set_iam_policy(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = CertificateAuthorityServiceClient( +def test_certificate_authority_service_grpc_lro_async_client(): + client = CertificateAuthorityServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc_asyncio", ) - request_init = {"resource": "projects/sample1/locations/sample2/caPools/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 = policy_pb2.Policy() + transport = client.transport - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_ca_pool_path(): + project = "squid" + location = "clam" + ca_pool = "whelk" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}".format( + project=project, + location=location, + ca_pool=ca_pool, + ) + actual = CertificateAuthorityServiceClient.ca_pool_path(project, location, ca_pool) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) +def test_parse_ca_pool_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ca_pool": "nudibranch", + } + path = CertificateAuthorityServiceClient.ca_pool_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_ca_pool_path(path) + assert expected == actual -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_certificate_path(): + project = "cuttlefish" + location = "mussel" + ca_pool = "winkle" + certificate = "nautilus" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificates/{certificate}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate=certificate, ) - - request = request_type() - request = json_format.ParseDict( - {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + actual = CertificateAuthorityServiceClient.certificate_path( + project, location, ca_pool, certificate ) + assert expected == actual - # 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.test_iam_permissions(request) +def test_parse_certificate_path(): + expected = { + "project": "scallop", + "location": "abalone", + "ca_pool": "squid", + "certificate": "clam", + } + path = CertificateAuthorityServiceClient.certificate_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"resource": "projects/sample1/locations/sample2/caPools/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 = iam_policy_pb2.TestIamPermissionsResponse() + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_certificate_authority_path(): + project = "whelk" + location = "octopus" + ca_pool = "oyster" + certificate_authority = "nudibranch" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate_authority=certificate_authority, + ) + actual = CertificateAuthorityServiceClient.certificate_authority_path( + project, location, ca_pool, certificate_authority + ) + assert expected == actual - response = client.test_iam_permissions(request) - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) +def test_parse_certificate_authority_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "ca_pool": "winkle", + "certificate_authority": "nautilus", + } + path = CertificateAuthorityServiceClient.certificate_authority_path(**expected) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_authority_path(path) + assert expected == actual -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_certificate_revocation_list_path(): + project = "scallop" + location = "abalone" + ca_pool = "squid" + certificate_authority = "clam" + certificate_revocation_list = "whelk" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}/certificateRevocationLists/{certificate_revocation_list}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate_authority=certificate_authority, + certificate_revocation_list=certificate_revocation_list, + ) + actual = CertificateAuthorityServiceClient.certificate_revocation_list_path( + project, location, ca_pool, certificate_authority, certificate_revocation_list ) + assert expected == actual - # 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.cancel_operation(request) +def test_parse_certificate_revocation_list_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ca_pool": "nudibranch", + "certificate_authority": "cuttlefish", + "certificate_revocation_list": "mussel", + } + path = CertificateAuthorityServiceClient.certificate_revocation_list_path( + **expected + ) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_revocation_list_path( + path ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_certificate_template_path(): + project = "winkle" + location = "nautilus" + certificate_template = "scallop" + expected = "projects/{project}/locations/{location}/certificateTemplates/{certificate_template}".format( + project=project, + location=location, + certificate_template=certificate_template, + ) + actual = CertificateAuthorityServiceClient.certificate_template_path( + project, location, certificate_template + ) + assert expected == actual - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_parse_certificate_template_path(): + expected = { + "project": "abalone", + "location": "squid", + "certificate_template": "clam", + } + path = CertificateAuthorityServiceClient.certificate_template_path(**expected) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_template_path(path) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + actual = CertificateAuthorityServiceClient.common_billing_account_path( + billing_account ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CertificateAuthorityServiceClient.common_billing_account_path(**expected) - # Establish that the response is the type that we expect. - assert response is None + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_billing_account_path(path) + assert expected == actual -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, ) + actual = CertificateAuthorityServiceClient.common_folder_path(folder) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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_operation(request) +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CertificateAuthorityServiceClient.common_folder_path(**expected) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_folder_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CertificateAuthorityServiceClient.common_organization_path(organization) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CertificateAuthorityServiceClient.common_organization_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_organization_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, ) + actual = CertificateAuthorityServiceClient.common_project_path(project) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # 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.list_operations(request) +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CertificateAuthorityServiceClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_project_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + actual = CertificateAuthorityServiceClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CertificateAuthorityServiceClient.common_location_path(**expected) - response = client.list_operations(request) + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CertificateAuthorityServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -26672,7 +27311,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -26725,7 +27364,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -26770,7 +27409,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -26811,7 +27450,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -26864,7 +27503,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -26909,7 +27548,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -26950,7 +27589,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27005,7 +27644,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27052,7 +27691,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -27095,7 +27734,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27150,7 +27789,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27197,7 +27836,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -27240,7 +27879,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27295,7 +27934,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27342,7 +27981,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -27385,7 +28024,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27440,7 +28079,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials() + credentials=async_anonymous_credentials() ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27487,7 +28126,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -27538,7 +28177,7 @@ def test_set_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27603,7 +28242,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27651,7 +28290,7 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio async def test_set_iam_policy_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: @@ -27704,7 +28343,7 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27770,7 +28409,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27818,7 +28457,7 @@ def test_get_iam_policy_from_dict(): @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: @@ -27870,7 +28509,7 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -27937,7 +28576,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -27991,7 +28630,7 @@ def test_test_iam_permissions_from_dict(): @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -28011,22 +28650,41 @@ async def test_test_iam_permissions_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py index 4c96ccd2ee1a..11c1bdfc4d63 100644 --- a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py +++ b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,16 +63,8 @@ from google.oauth2 import service_account from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore -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.security.privateca_v1beta1.services.certificate_authority_service import ( CertificateAuthorityServiceAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.security.privateca_v1beta1.types import resources, service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1262,27 +1285,6 @@ def test_create_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_create_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateRequest() - - def test_create_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1356,33 +1358,6 @@ def test_create_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.create_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateRequest() - - @pytest.mark.asyncio async def test_create_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1391,7 +1366,7 @@ async def test_create_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1430,7 +1405,7 @@ async def test_create_certificate_async( transport: str = "grpc_asyncio", request_type=service.CreateCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1504,7 +1479,7 @@ def test_create_certificate_field_headers(): @pytest.mark.asyncio async def test_create_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1588,7 +1563,7 @@ def test_create_certificate_flattened_error(): @pytest.mark.asyncio async def test_create_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1627,7 +1602,7 @@ async def test_create_certificate_flattened_async(): @pytest.mark.asyncio async def test_create_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1682,25 +1657,6 @@ def test_get_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_get_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRequest() - - def test_get_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1764,31 +1720,6 @@ def test_get_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.get_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRequest() - - @pytest.mark.asyncio async def test_get_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1797,7 +1728,7 @@ async def test_get_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1836,7 +1767,7 @@ async def test_get_certificate_async( transport: str = "grpc_asyncio", request_type=service.GetCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1906,7 +1837,7 @@ def test_get_certificate_field_headers(): @pytest.mark.asyncio async def test_get_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1976,7 +1907,7 @@ def test_get_certificate_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2005,7 +1936,7 @@ async def test_get_certificate_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2057,27 +1988,6 @@ def test_list_certificates(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_certificates_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificates), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificatesRequest() - - def test_list_certificates_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2151,32 +2061,6 @@ def test_list_certificates_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificates_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificates), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificatesRequest() - - @pytest.mark.asyncio async def test_list_certificates_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2185,7 +2069,7 @@ async def test_list_certificates_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2224,7 +2108,7 @@ async def test_list_certificates_async( transport: str = "grpc_asyncio", request_type=service.ListCertificatesRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2296,7 +2180,7 @@ def test_list_certificates_field_headers(): @pytest.mark.asyncio async def test_list_certificates_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2370,7 +2254,7 @@ def test_list_certificates_flattened_error(): @pytest.mark.asyncio async def test_list_certificates_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2401,7 +2285,7 @@ async def test_list_certificates_flattened_async(): @pytest.mark.asyncio async def test_list_certificates_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2515,7 +2399,7 @@ def test_list_certificates_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificates_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2567,7 +2451,7 @@ async def test_list_certificates_async_pager(): @pytest.mark.asyncio async def test_list_certificates_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2658,27 +2542,6 @@ def test_revoke_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_revoke_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.revoke_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.revoke_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RevokeCertificateRequest() - - def test_revoke_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2750,33 +2613,6 @@ def test_revoke_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_revoke_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.revoke_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.revoke_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RevokeCertificateRequest() - - @pytest.mark.asyncio async def test_revoke_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2785,7 +2621,7 @@ async def test_revoke_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2824,7 +2660,7 @@ async def test_revoke_certificate_async( transport: str = "grpc_asyncio", request_type=service.RevokeCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2898,7 +2734,7 @@ def test_revoke_certificate_field_headers(): @pytest.mark.asyncio async def test_revoke_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2972,7 +2808,7 @@ def test_revoke_certificate_flattened_error(): @pytest.mark.asyncio async def test_revoke_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3003,7 +2839,7 @@ async def test_revoke_certificate_flattened_async(): @pytest.mark.asyncio async def test_revoke_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3058,27 +2894,6 @@ def test_update_certificate(request_type, transport: str = "grpc"): assert response.pem_certificate_chain == ["pem_certificate_chain_value"] -def test_update_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRequest() - - def test_update_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3148,33 +2963,6 @@ def test_update_certificate_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - ) - ) - response = await client.update_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRequest() - - @pytest.mark.asyncio async def test_update_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3183,7 +2971,7 @@ async def test_update_certificate_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3222,7 +3010,7 @@ async def test_update_certificate_async( transport: str = "grpc_asyncio", request_type=service.UpdateCertificateRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3296,7 +3084,7 @@ def test_update_certificate_field_headers(): @pytest.mark.asyncio async def test_update_certificate_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3375,7 +3163,7 @@ def test_update_certificate_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3410,7 +3198,7 @@ async def test_update_certificate_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3458,27 +3246,6 @@ def test_activate_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_activate_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.activate_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.activate_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ActivateCertificateAuthorityRequest() - - def test_activate_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3558,29 +3325,6 @@ def test_activate_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_activate_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.activate_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.activate_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ActivateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_activate_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3589,7 +3333,7 @@ async def test_activate_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3634,7 +3378,7 @@ async def test_activate_certificate_authority_async( request_type=service.ActivateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3701,7 +3445,7 @@ def test_activate_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_activate_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3775,7 +3519,7 @@ def test_activate_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_activate_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3806,7 +3550,7 @@ async def test_activate_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_activate_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3853,27 +3597,6 @@ def test_create_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateAuthorityRequest() - - def test_create_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3953,29 +3676,6 @@ def test_create_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_create_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3984,7 +3684,7 @@ async def test_create_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4029,7 +3729,7 @@ async def test_create_certificate_authority_async( request_type=service.CreateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4096,7 +3796,7 @@ def test_create_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_create_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4180,7 +3880,7 @@ def test_create_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_create_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4219,7 +3919,7 @@ async def test_create_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_create_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4268,27 +3968,6 @@ def test_disable_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_disable_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.disable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DisableCertificateAuthorityRequest() - - def test_disable_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4366,29 +4045,6 @@ def test_disable_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_disable_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.disable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DisableCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_disable_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4397,7 +4053,7 @@ async def test_disable_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4442,7 +4098,7 @@ async def test_disable_certificate_authority_async( request_type=service.DisableCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4509,7 +4165,7 @@ def test_disable_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_disable_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4583,7 +4239,7 @@ def test_disable_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_disable_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4614,7 +4270,7 @@ async def test_disable_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_disable_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4661,27 +4317,6 @@ def test_enable_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_enable_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.enable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EnableCertificateAuthorityRequest() - - def test_enable_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4759,29 +4394,6 @@ def test_enable_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_enable_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.enable_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EnableCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_enable_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4790,7 +4402,7 @@ async def test_enable_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4835,7 +4447,7 @@ async def test_enable_certificate_authority_async( request_type=service.EnableCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4902,7 +4514,7 @@ def test_enable_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_enable_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4976,7 +4588,7 @@ def test_enable_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_enable_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5007,7 +4619,7 @@ async def test_enable_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_enable_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5057,27 +4669,6 @@ def test_fetch_certificate_authority_csr(request_type, transport: str = "grpc"): assert response.pem_csr == "pem_csr_value" -def test_fetch_certificate_authority_csr_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_certificate_authority_csr), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_certificate_authority_csr() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCertificateAuthorityCsrRequest() - - def test_fetch_certificate_authority_csr_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5148,31 +4739,6 @@ def test_fetch_certificate_authority_csr_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_fetch_certificate_authority_csr_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_certificate_authority_csr), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.FetchCertificateAuthorityCsrResponse( - pem_csr="pem_csr_value", - ) - ) - response = await client.fetch_certificate_authority_csr() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.FetchCertificateAuthorityCsrRequest() - - @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5181,7 +4747,7 @@ async def test_fetch_certificate_authority_csr_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5221,7 +4787,7 @@ async def test_fetch_certificate_authority_csr_async( request_type=service.FetchCertificateAuthorityCsrRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5291,7 +4857,7 @@ def test_fetch_certificate_authority_csr_field_headers(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5365,7 +4931,7 @@ def test_fetch_certificate_authority_csr_flattened_error(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5396,7 +4962,7 @@ async def test_fetch_certificate_authority_csr_flattened_async(): @pytest.mark.asyncio async def test_fetch_certificate_authority_csr_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5456,27 +5022,6 @@ def test_get_certificate_authority(request_type, transport: str = "grpc"): assert response.gcs_bucket == "gcs_bucket_value" -def test_get_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateAuthorityRequest() - - def test_get_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5547,36 +5092,6 @@ def test_get_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CertificateAuthority( - name="name_value", - type_=resources.CertificateAuthority.Type.SELF_SIGNED, - tier=resources.CertificateAuthority.Tier.ENTERPRISE, - state=resources.CertificateAuthority.State.ENABLED, - pem_ca_certificates=["pem_ca_certificates_value"], - gcs_bucket="gcs_bucket_value", - ) - ) - response = await client.get_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_get_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5585,7 +5100,7 @@ async def test_get_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5624,7 +5139,7 @@ async def test_get_certificate_authority_async( transport: str = "grpc_asyncio", request_type=service.GetCertificateAuthorityRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5704,7 +5219,7 @@ def test_get_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_get_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5778,7 +5293,7 @@ def test_get_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5809,7 +5324,7 @@ async def test_get_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5861,27 +5376,6 @@ def test_list_certificate_authorities(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_certificate_authorities_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_authorities), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificate_authorities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateAuthoritiesRequest() - - def test_list_certificate_authorities_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5959,42 +5453,16 @@ def test_list_certificate_authorities_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_certificate_authorities_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_authorities), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificateAuthoritiesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificate_authorities() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateAuthoritiesRequest() - - -@pytest.mark.asyncio -async def test_list_certificate_authorities_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_list_certificate_authorities_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -6032,7 +5500,7 @@ async def test_list_certificate_authorities_async( request_type=service.ListCertificateAuthoritiesRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6104,7 +5572,7 @@ def test_list_certificate_authorities_field_headers(): @pytest.mark.asyncio async def test_list_certificate_authorities_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6178,7 +5646,7 @@ def test_list_certificate_authorities_flattened_error(): @pytest.mark.asyncio async def test_list_certificate_authorities_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6209,7 +5677,7 @@ async def test_list_certificate_authorities_flattened_async(): @pytest.mark.asyncio async def test_list_certificate_authorities_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6325,7 +5793,7 @@ def test_list_certificate_authorities_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificate_authorities_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6377,7 +5845,7 @@ async def test_list_certificate_authorities_async_pager(): @pytest.mark.asyncio async def test_list_certificate_authorities_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6460,27 +5928,6 @@ def test_restore_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_restore_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.restore_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCertificateAuthorityRequest() - - def test_restore_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6558,29 +6005,6 @@ def test_restore_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_restore_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.restore_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_restore_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6589,7 +6013,7 @@ async def test_restore_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6634,7 +6058,7 @@ async def test_restore_certificate_authority_async( request_type=service.RestoreCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6701,7 +6125,7 @@ def test_restore_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_restore_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6775,7 +6199,7 @@ def test_restore_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_restore_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6806,7 +6230,7 @@ async def test_restore_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_restore_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6853,27 +6277,6 @@ def test_schedule_delete_certificate_authority(request_type, transport: str = "g assert isinstance(response, future.Future) -def test_schedule_delete_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_delete_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.schedule_delete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ScheduleDeleteCertificateAuthorityRequest() - - def test_schedule_delete_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6951,29 +6354,6 @@ def test_schedule_delete_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_schedule_delete_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.schedule_delete_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.schedule_delete_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ScheduleDeleteCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_schedule_delete_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6982,7 +6362,7 @@ async def test_schedule_delete_certificate_authority_async_use_cached_wrapped_rp # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7027,7 +6407,7 @@ async def test_schedule_delete_certificate_authority_async( request_type=service.ScheduleDeleteCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7094,7 +6474,7 @@ def test_schedule_delete_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_schedule_delete_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7168,7 +6548,7 @@ def test_schedule_delete_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_schedule_delete_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7199,7 +6579,7 @@ async def test_schedule_delete_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_schedule_delete_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7246,27 +6626,6 @@ def test_update_certificate_authority(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateAuthorityRequest() - - def test_update_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7342,29 +6701,6 @@ def test_update_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_update_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7373,7 +6709,7 @@ async def test_update_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7418,7 +6754,7 @@ async def test_update_certificate_authority_async( request_type=service.UpdateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7485,7 +6821,7 @@ def test_update_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_update_certificate_authority_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7564,7 +6900,7 @@ def test_update_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_authority_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7599,7 +6935,7 @@ async def test_update_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_authority_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7658,27 +6994,6 @@ def test_get_certificate_revocation_list(request_type, transport: str = "grpc"): assert response.state == resources.CertificateRevocationList.State.ACTIVE -def test_get_certificate_revocation_list_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_revocation_list), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRevocationListRequest() - - def test_get_certificate_revocation_list_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7749,35 +7064,6 @@ def test_get_certificate_revocation_list_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_certificate_revocation_list_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_revocation_list), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CertificateRevocationList( - name="name_value", - sequence_number=1601, - pem_crl="pem_crl_value", - access_url="access_url_value", - state=resources.CertificateRevocationList.State.ACTIVE, - ) - ) - response = await client.get_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCertificateRevocationListRequest() - - @pytest.mark.asyncio async def test_get_certificate_revocation_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7786,7 +7072,7 @@ async def test_get_certificate_revocation_list_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7826,7 +7112,7 @@ async def test_get_certificate_revocation_list_async( request_type=service.GetCertificateRevocationListRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7904,7 +7190,7 @@ def test_get_certificate_revocation_list_field_headers(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7978,7 +7264,7 @@ def test_get_certificate_revocation_list_flattened_error(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8009,7 +7295,7 @@ async def test_get_certificate_revocation_list_flattened_async(): @pytest.mark.asyncio async def test_get_certificate_revocation_list_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8061,27 +7347,6 @@ def test_list_certificate_revocation_lists(request_type, transport: str = "grpc" assert response.unreachable == ["unreachable_value"] -def test_list_certificate_revocation_lists_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_revocation_lists), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_certificate_revocation_lists() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateRevocationListsRequest() - - def test_list_certificate_revocation_lists_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8158,32 +7423,6 @@ def test_list_certificate_revocation_lists_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_certificate_revocation_lists_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_certificate_revocation_lists), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListCertificateRevocationListsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_certificate_revocation_lists() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCertificateRevocationListsRequest() - - @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8192,7 +7431,7 @@ async def test_list_certificate_revocation_lists_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8232,7 +7471,7 @@ async def test_list_certificate_revocation_lists_async( request_type=service.ListCertificateRevocationListsRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8304,7 +7543,7 @@ def test_list_certificate_revocation_lists_field_headers(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8378,7 +7617,7 @@ def test_list_certificate_revocation_lists_flattened_error(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8409,7 +7648,7 @@ async def test_list_certificate_revocation_lists_flattened_async(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8525,7 +7764,7 @@ def test_list_certificate_revocation_lists_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8579,7 +7818,7 @@ async def test_list_certificate_revocation_lists_async_pager(): @pytest.mark.asyncio async def test_list_certificate_revocation_lists_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8662,27 +7901,6 @@ def test_update_certificate_revocation_list(request_type, transport: str = "grpc assert isinstance(response, future.Future) -def test_update_certificate_revocation_list_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_revocation_list), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRevocationListRequest() - - def test_update_certificate_revocation_list_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8758,29 +7976,6 @@ def test_update_certificate_revocation_list_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_certificate_revocation_list_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_certificate_revocation_list), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_certificate_revocation_list() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCertificateRevocationListRequest() - - @pytest.mark.asyncio async def test_update_certificate_revocation_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8789,7 +7984,7 @@ async def test_update_certificate_revocation_list_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8834,7 +8029,7 @@ async def test_update_certificate_revocation_list_async( request_type=service.UpdateCertificateRevocationListRequest, ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8901,7 +8096,7 @@ def test_update_certificate_revocation_list_field_headers(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8984,7 +8179,7 @@ def test_update_certificate_revocation_list_flattened_error(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9021,7 +8216,7 @@ async def test_update_certificate_revocation_list_flattened_async(): @pytest.mark.asyncio async def test_update_certificate_revocation_list_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9076,27 +8271,6 @@ def test_get_reusable_config(request_type, transport: str = "grpc"): assert response.description == "description_value" -def test_get_reusable_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_reusable_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_reusable_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetReusableConfigRequest() - - def test_get_reusable_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -9166,32 +8340,6 @@ def test_get_reusable_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_reusable_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_reusable_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ReusableConfig( - name="name_value", - description="description_value", - ) - ) - response = await client.get_reusable_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetReusableConfigRequest() - - @pytest.mark.asyncio async def test_get_reusable_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -9200,7 +8348,7 @@ async def test_get_reusable_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9239,7 +8387,7 @@ async def test_get_reusable_config_async( transport: str = "grpc_asyncio", request_type=service.GetReusableConfigRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9311,7 +8459,7 @@ def test_get_reusable_config_field_headers(): @pytest.mark.asyncio async def test_get_reusable_config_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9385,7 +8533,7 @@ def test_get_reusable_config_flattened_error(): @pytest.mark.asyncio async def test_get_reusable_config_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9416,7 +8564,7 @@ async def test_get_reusable_config_flattened_async(): @pytest.mark.asyncio async def test_get_reusable_config_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9468,27 +8616,6 @@ def test_list_reusable_configs(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_reusable_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_reusable_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_reusable_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListReusableConfigsRequest() - - def test_list_reusable_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -9565,32 +8692,6 @@ def test_list_reusable_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_reusable_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_reusable_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListReusableConfigsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_reusable_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListReusableConfigsRequest() - - @pytest.mark.asyncio async def test_list_reusable_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -9599,7 +8700,7 @@ async def test_list_reusable_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9638,7 +8739,7 @@ async def test_list_reusable_configs_async( transport: str = "grpc_asyncio", request_type=service.ListReusableConfigsRequest ): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9710,7 +8811,7 @@ def test_list_reusable_configs_field_headers(): @pytest.mark.asyncio async def test_list_reusable_configs_field_headers_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9784,7 +8885,7 @@ def test_list_reusable_configs_flattened_error(): @pytest.mark.asyncio async def test_list_reusable_configs_flattened_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9815,7 +8916,7 @@ async def test_list_reusable_configs_flattened_async(): @pytest.mark.asyncio async def test_list_reusable_configs_flattened_error_async(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9929,7 +9030,7 @@ def test_list_reusable_configs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_reusable_configs_async_pager(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9981,7 +9082,7 @@ async def test_list_reusable_configs_async_pager(): @pytest.mark.asyncio async def test_list_reusable_configs_async_pages(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -10029,210 +9130,173 @@ async def test_list_reusable_configs_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCertificateRequest, - dict, - ], -) -def test_create_certificate_rest(request_type): +def test_create_certificate_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_certificate in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_certificate + ] = mock_rpc + + request = {} + client.create_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_certificate(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_certificate_rest_required_fields( + request_type=service.CreateCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._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_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_id", + "request_id", + ) + ) + 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 = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - request_init["certificate"] = { - "name": "name_value", - "pem_csr": "pem_csr_value", - "config": { - "subject_config": { - "subject": { - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "common_name": "common_name_value", - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "reusable_config": { - "reusable_config": "reusable_config_value", - "reusable_config_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": { - "is_ca": {"value": True}, - "max_issuer_path_length": {"value": 541}, - }, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "additional_extensions": {}, - }, - }, - "public_key": {"type_": 1, "key": b"key_blob"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "revocation_details": { - "revocation_state": 1, - "revocation_time": {"seconds": 751, "nanos": 543}, - }, - "pem_certificate": "pem_certificate_value", - "certificate_description": { - "subject_description": { - "subject": {}, - "common_name": "common_name_value", - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {}, - "not_after_time": {}, - }, - "config_values": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - }, - "pem_certificate_chain": [ - "pem_certificate_chain_value1", - "pem_certificate_chain_value2", - ], - "create_time": {}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCertificateRequest.meta.fields["certificate"] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.create_certificate(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["certificate"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_create_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.create_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateId", + "requestId", + ) + ) + & set( + ( + "parent", + "certificate", + ) + ) + ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate"][field])): - del request_init["certificate"][field][i][subfield] - else: - del request_init["certificate"][field][subfield] - request = request_type(**request_init) + +def test_create_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -10240,19 +9304,40 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_certificate(request) - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + client.create_certificate(**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/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" + % client.transport._host, + args[1], + ) -def test_create_certificate_rest_use_cached_wrapped_rpc(): +def test_create_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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_certificate( + service.CreateCertificateRequest(), + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) + + +def test_get_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10266,39 +9351,35 @@ def test_create_certificate_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_certificate in client._transport._wrapped_methods - ) + assert client._transport.get_certificate in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_certificate - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_certificate] = mock_rpc request = {} - client.create_certificate(request) + client.get_certificate(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_certificate(request) + client.get_certificate(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_certificate_rest_required_fields( - request_type=service.CreateCertificateRequest, +def test_get_certificate_rest_required_fields( + request_type=service.GetCertificateRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10309,28 +9390,21 @@ def test_create_certificate_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_certificate._get_unset_required_fields(jsonified_request) + ).get_certificate._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_certificate._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "certificate_id", - "request_id", - ) - ) + ).get_certificate._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" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10351,10 +9425,9 @@ def test_create_certificate_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10367,119 +9440,23 @@ def test_create_certificate_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_certificate(request) + response = client.get_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_certificate_rest_unset_required_fields(): +def test_get_certificate_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_certificate._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "certificateId", - "requestId", - ) - ) - & set( - ( - "parent", - "certificate", - ) - ) - ) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCertificateRequest.pb( - service.CreateCertificateRequest() - ) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.CreateCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.create_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_certificate_rest_bad_request( - transport: str = "rest", request_type=service.CreateCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/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.create_certificate(request) + unset_fields = transport.get_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_certificate_rest_flattened(): +def test_get_certificate_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10492,14 +9469,12 @@ def test_create_certificate_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - certificate=resources.Certificate(name="name_value"), - certificate_id="certificate_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -10512,20 +9487,20 @@ def test_create_certificate_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_certificate(**mock_args) + client.get_certificate(**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/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" % client.transport._host, args[1], ) -def test_create_certificate_rest_flattened_error(transport: str = "rest"): +def test_get_certificate_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10534,68 +9509,13 @@ def test_create_certificate_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_certificate( - service.CreateCertificateRequest(), - parent="parent_value", - certificate=resources.Certificate(name="name_value"), - certificate_id="certificate_id_value", - ) - - -def test_create_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetCertificateRequest, - dict, - ], -) -def test_get_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - 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 = resources.Certificate( + client.get_certificate( + service.GetCertificateRequest(), name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - -def test_get_certificate_rest_use_cached_wrapped_rpc(): +def test_list_certificates_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10609,35 +9529,37 @@ def test_get_certificate_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_certificate in client._transport._wrapped_methods + assert client._transport.list_certificates in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_certificate] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_certificates + ] = mock_rpc request = {} - client.get_certificate(request) + client.list_certificates(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_certificate(request) + client.list_certificates(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_certificate_rest_required_fields( - request_type=service.GetCertificateRequest, +def test_list_certificates_rest_required_fields( + request_type=service.ListCertificatesRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10648,21 +9570,30 @@ def test_get_certificate_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_certificate._get_unset_required_fields(jsonified_request) + ).list_certificates._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_certificate._get_unset_required_fields(jsonified_request) + ).list_certificates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10671,7 +9602,7 @@ def test_get_certificate_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Certificate() + return_value = service.ListCertificatesResponse() # 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 @@ -10692,128 +9623,57 @@ def test_get_certificate_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) + return_value = service.ListCertificatesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_certificate(request) + response = client.list_certificates(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_certificate_rest_unset_required_fields(): +def test_list_certificates_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_certificate._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_certificates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_list_certificates_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.GetCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.get_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_certificate_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - 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_certificate(request) - - -def test_get_certificate_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = resources.Certificate() + return_value = service.ListCertificatesResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -10821,25 +9681,25 @@ def test_get_certificate_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) + return_value = service.ListCertificatesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_certificate(**mock_args) + client.list_certificates(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" + "%s/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" % client.transport._host, args[1], ) -def test_get_certificate_rest_flattened_error(transport: str = "rest"): +def test_list_certificates_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10848,63 +9708,76 @@ def test_get_certificate_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_certificate( - service.GetCertificateRequest(), - name="name_value", + client.list_certificates( + service.ListCertificatesRequest(), + parent="parent_value", ) -def test_get_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificatesRequest, - dict, - ], -) -def test_list_certificates_rest(request_type): +def test_list_certificates_rest_pager(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/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 = service.ListCertificatesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + resources.Certificate(), + ], + next_page_token="abc", + ), + service.ListCertificatesResponse( + certificates=[], + next_page_token="def", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + ], + next_page_token="ghi", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + ], + ), ) + # Two responses for two calls + response = response + response - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Wrap the values into proper Response objs + response = tuple(service.ListCertificatesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_certificates(request) + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificatesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + pager = client.list_certificates(request=sample_request) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Certificate) for i in results) -def test_list_certificates_rest_use_cached_wrapped_rpc(): + pages = list(client.list_certificates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_revoke_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10918,7 +9791,9 @@ def test_list_certificates_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_certificates in client._transport._wrapped_methods + assert ( + client._transport.revoke_certificate in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -10926,29 +9801,29 @@ def test_list_certificates_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_certificates + client._transport.revoke_certificate ] = mock_rpc request = {} - client.list_certificates(request) + client.revoke_certificate(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_certificates(request) + client.revoke_certificate(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_certificates_rest_required_fields( - request_type=service.ListCertificatesRequest, +def test_revoke_certificate_rest_required_fields( + request_type=service.RevokeCertificateRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10959,30 +9834,21 @@ def test_list_certificates_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_certificates._get_unset_required_fields(jsonified_request) + ).revoke_certificate._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_certificates._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) + ).revoke_certificate._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" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10991,7 +9857,7 @@ def test_list_certificates_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListCertificatesResponse() + return_value = resources.Certificate() # 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 @@ -11003,149 +9869,65 @@ def test_list_certificates_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCertificatesResponse.pb(return_value) + return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_certificates(request) + response = client.revoke_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_certificates_rest_unset_required_fields(): +def test_revoke_certificate_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_certificates._get_unset_required_fields({}) + unset_fields = transport.revoke_certificate._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "name", + "reason", ) ) - & set(("parent",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificates_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_revoke_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCertificatesRequest.pb( - service.ListCertificatesRequest() - ) - 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 = service.ListCertificatesResponse.to_json( - service.ListCertificatesResponse() - ) - - request = service.ListCertificatesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCertificatesResponse() - - client.list_certificates( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_certificates_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificatesRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/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.list_certificates(request) - - -def test_list_certificates_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = service.ListCertificatesResponse() + return_value = resources.Certificate() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -11153,25 +9935,25 @@ def test_list_certificates_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCertificatesResponse.pb(return_value) + return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_certificates(**mock_args) + client.revoke_certificate(**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/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke" % client.transport._host, args[1], ) -def test_list_certificates_rest_flattened_error(transport: str = "rest"): +def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11180,123 +9962,13 @@ def test_list_certificates_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_certificates( - service.ListCertificatesRequest(), - parent="parent_value", - ) - - -def test_list_certificates_rest_pager(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListCertificatesResponse( - certificates=[ - resources.Certificate(), - resources.Certificate(), - resources.Certificate(), - ], - next_page_token="abc", - ), - service.ListCertificatesResponse( - certificates=[], - next_page_token="def", - ), - service.ListCertificatesResponse( - certificates=[ - resources.Certificate(), - ], - next_page_token="ghi", - ), - service.ListCertificatesResponse( - certificates=[ - resources.Certificate(), - resources.Certificate(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListCertificatesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - - pager = client.list_certificates(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Certificate) for i in results) - - pages = list(client.list_certificates(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - service.RevokeCertificateRequest, - dict, - ], -) -def test_revoke_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - 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 = resources.Certificate( + client.revoke_certificate( + service.RevokeCertificateRequest(), name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.revoke_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - -def test_revoke_certificate_rest_use_cached_wrapped_rpc(): +def test_update_certificate_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11311,7 +9983,7 @@ def test_revoke_certificate_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.revoke_certificate in client._transport._wrapped_methods + client._transport.update_certificate in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11320,29 +9992,28 @@ def test_revoke_certificate_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.revoke_certificate + client._transport.update_certificate ] = mock_rpc request = {} - client.revoke_certificate(request) + client.update_certificate(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.revoke_certificate(request) + client.update_certificate(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_revoke_certificate_rest_required_fields( - request_type=service.RevokeCertificateRequest, +def test_update_certificate_rest_required_fields( + request_type=service.UpdateCertificateRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11353,21 +10024,24 @@ def test_revoke_certificate_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).revoke_certificate._get_unset_required_fields(jsonified_request) + ).update_certificate._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() - ).revoke_certificate._get_unset_required_fields(jsonified_request) + ).update_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_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 = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11388,7 +10062,7 @@ def test_revoke_certificate_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -11404,114 +10078,240 @@ def test_revoke_certificate_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.revoke_certificate(request) + response = client.update_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_revoke_certificate_rest_unset_required_fields(): +def test_update_certificate_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.revoke_certificate._get_unset_required_fields({}) + unset_fields = transport.update_certificate._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "requestId", + "updateMask", + ) + ) & set( ( - "name", - "reason", + "certificate", + "updateMask", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_revoke_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_update_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.RevokeCertificateRequest.pb( - service.RevokeCertificateRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.Certificate.to_json( - resources.Certificate() + # get truthy value for each flattened field + mock_args = dict( + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + mock_args.update(sample_request) - request = service.RevokeCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.revoke_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_certificate(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" + % client.transport._host, + args[1], + ) -def test_revoke_certificate_rest_bad_request( - transport: str = "rest", request_type=service.RevokeCertificateRequest -): +def test_update_certificate_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate( + service.UpdateCertificateRequest(), + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.activate_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.activate_certificate_authority + ] = mock_rpc + + request = {} + client.activate_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.activate_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_activate_certificate_authority_rest_required_fields( + request_type=service.ActivateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pem_ca_certificate"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # 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.revoke_certificate(request) + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_revoke_certificate_rest_flattened(): + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pemCaCertificate"] = "pem_ca_certificate_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._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 "pemCaCertificate" in jsonified_request + assert jsonified_request["pemCaCertificate"] == "pem_ca_certificate_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.activate_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_activate_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.activate_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "pemCaCertificate", + "subordinateConfig", + ) + ) + ) + + +def test_activate_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11520,11 +10320,11 @@ def test_revoke_certificate_rest_flattened(): # 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 = resources.Certificate() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } # get truthy value for each flattened field @@ -11536,26 +10336,24 @@ def test_revoke_certificate_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.revoke_certificate(**mock_args) + client.activate_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke" + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate" % client.transport._host, args[1], ) -def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): +def test_activate_certificate_authority_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11564,259 +10362,29 @@ def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.revoke_certificate( - service.RevokeCertificateRequest(), + client.activate_certificate_authority( + service.ActivateCertificateAuthorityRequest(), name="name_value", ) -def test_revoke_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateCertificateRequest, - dict, - ], -) -def test_update_certificate_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - } - request_init["certificate"] = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4", - "pem_csr": "pem_csr_value", - "config": { - "subject_config": { - "subject": { - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "common_name": "common_name_value", - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "reusable_config": { - "reusable_config": "reusable_config_value", - "reusable_config_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": { - "is_ca": {"value": True}, - "max_issuer_path_length": {"value": 541}, - }, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "additional_extensions": {}, - }, - }, - "public_key": {"type_": 1, "key": b"key_blob"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "revocation_details": { - "revocation_state": 1, - "revocation_time": {"seconds": 751, "nanos": 543}, - }, - "pem_certificate": "pem_certificate_value", - "certificate_description": { - "subject_description": { - "subject": {}, - "common_name": "common_name_value", - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {}, - "not_after_time": {}, - }, - "config_values": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - }, - "pem_certificate_chain": [ - "pem_certificate_chain_value1", - "pem_certificate_chain_value2", - ], - "create_time": {}, - "update_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateRequest.meta.fields["certificate"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["certificate"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate"][field])): - del request_init["certificate"][field][i][subfield] - else: - del request_init["certificate"][field][subfield] - 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 = resources.Certificate( - name="name_value", - pem_certificate="pem_certificate_value", - pem_certificate_chain=["pem_certificate_chain_value"], - pem_csr="pem_csr_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Certificate) - assert response.name == "name_value" - assert response.pem_certificate == "pem_certificate_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - - -def test_update_certificate_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( - client._transport.update_certificate in client._transport._wrapped_methods + client._transport.create_certificate_authority + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11825,28 +10393,34 @@ def test_update_certificate_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_certificate + client._transport.create_certificate_authority ] = mock_rpc request = {} - client.update_certificate(request) + client.create_certificate_authority(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_certificate(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_certificate_authority(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_certificate_rest_required_fields( - request_type=service.UpdateCertificateRequest, +def test_create_certificate_authority_rest_required_fields( + request_type=service.CreateCertificateAuthorityRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} + request_init["parent"] = "" + request_init["certificate_authority_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11854,27 +10428,42 @@ def test_update_certificate_rest_required_fields( ) # verify fields with default values are dropped + assert "certificateAuthorityId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_certificate._get_unset_required_fields(jsonified_request) + ).create_certificate_authority._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] + == request_init["certificate_authority_id"] + ) - unset_fields = transport_class( + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateAuthorityId"] = "certificate_authority_id_value" + + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_certificate._get_unset_required_fields(jsonified_request) + ).create_certificate_authority._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "certificate_authority_id", "request_id", - "update_mask", ) ) 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" + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] == "certificate_authority_id_value" + ) client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11883,7 +10472,7 @@ def test_update_certificate_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Certificate() + return_value = operations_pb2.Operation(name="operations/spam") # 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 @@ -11895,7 +10484,7 @@ def test_update_certificate_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -11903,129 +10492,48 @@ def test_update_certificate_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_certificate(request) + response = client.create_certificate_authority(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "certificateAuthorityId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_certificate_rest_unset_required_fields(): +def test_create_certificate_authority_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_certificate._get_unset_required_fields({}) + unset_fields = transport.create_certificate_authority._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "certificateAuthorityId", "requestId", - "updateMask", ) ) & set( ( - "certificate", - "updateMask", + "parent", + "certificateAuthorityId", + "certificateAuthority", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCertificateRequest.pb( - service.UpdateCertificateRequest() - ) - 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 = resources.Certificate.to_json( - resources.Certificate() - ) - - request = service.UpdateCertificateRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Certificate() - - client.update_certificate( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_certificate_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateRequest -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - } - 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_certificate(request) - - -def test_update_certificate_rest_flattened(): +def test_create_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12034,45 +10542,40 @@ def test_update_certificate_rest_flattened(): # 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 = resources.Certificate() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "certificate": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" - } - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - certificate=resources.Certificate(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_certificate(**mock_args) + client.create_certificate_authority(**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/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" + "%s/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" % client.transport._host, args[1], ) -def test_update_certificate_rest_flattened_error(transport: str = "rest"): +def test_create_certificate_authority_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12081,57 +10584,15 @@ def test_update_certificate_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_certificate( - service.UpdateCertificateRequest(), - certificate=resources.Certificate(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_certificate_authority( + service.CreateCertificateAuthorityRequest(), + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", ) -def test_update_certificate_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ActivateCertificateAuthorityRequest, - dict, - ], -) -def test_activate_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.activate_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): +def test_disable_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12146,7 +10607,7 @@ def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.activate_certificate_authority + client._transport.disable_certificate_authority in client._transport._wrapped_methods ) @@ -12156,11 +10617,11 @@ def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.activate_certificate_authority + client._transport.disable_certificate_authority ] = mock_rpc request = {} - client.activate_certificate_authority(request) + client.disable_certificate_authority(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -12169,21 +10630,20 @@ def test_activate_certificate_authority_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.activate_certificate_authority(request) + client.disable_certificate_authority(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_activate_certificate_authority_rest_required_fields( - request_type=service.ActivateCertificateAuthorityRequest, +def test_disable_certificate_authority_rest_required_fields( + request_type=service.DisableCertificateAuthorityRequest, ): transport_class = transports.CertificateAuthorityServiceRestTransport request_init = {} request_init["name"] = "" - request_init["pem_ca_certificate"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12194,24 +10654,21 @@ def test_activate_certificate_authority_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + ).disable_certificate_authority._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["pemCaCertificate"] = "pem_ca_certificate_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + ).disable_certificate_authority._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 "pemCaCertificate" in jsonified_request - assert jsonified_request["pemCaCertificate"] == "pem_ca_certificate_value" client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12245,121 +10702,208 @@ def test_activate_certificate_authority_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.activate_certificate_authority(request) + response = client.disable_certificate_authority(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_activate_certificate_authority_rest_unset_required_fields(): +def test_disable_certificate_authority_rest_unset_required_fields(): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.activate_certificate_authority._get_unset_required_fields( + unset_fields = transport.disable_certificate_authority._get_unset_required_fields( {} ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "pemCaCertificate", - "subordinateConfig", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_activate_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( +def test_disable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_activate_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_activate_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ActivateCertificateAuthorityRequest.pb( - service.ActivateCertificateAuthorityRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - request = service.ActivateCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.activate_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.disable_certificate_authority(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable" + % client.transport._host, + args[1], + ) -def test_activate_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.ActivateCertificateAuthorityRequest -): +def test_disable_certificate_authority_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_certificate_authority( + service.DisableCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_enable_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.enable_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.enable_certificate_authority + ] = mock_rpc + + request = {} + client.enable_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.enable_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_enable_certificate_authority_rest_required_fields( + request_type=service.EnableCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_certificate_authority._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() + ).enable_certificate_authority._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) 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.activate_certificate_authority(request) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_activate_certificate_authority_rest_flattened(): + response = client.enable_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_enable_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.enable_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_enable_certificate_authority_rest_flattened(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12388,20 +10932,20 @@ def test_activate_certificate_authority_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.activate_certificate_authority(**mock_args) + client.enable_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate" + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable" % client.transport._host, args[1], ) -def test_activate_certificate_authority_rest_flattened_error(transport: str = "rest"): +def test_enable_certificate_authority_rest_flattened_error(transport: str = "rest"): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12410,835 +10954,3514 @@ def test_activate_certificate_authority_rest_flattened_error(transport: str = "r # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.activate_certificate_authority( - service.ActivateCertificateAuthorityRequest(), + client.enable_certificate_authority( + service.EnableCertificateAuthorityRequest(), name="name_value", ) -def test_activate_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_fetch_certificate_authority_csr_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - service.CreateCertificateAuthorityRequest, - dict, - ], -) -def test_create_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert ( + client._transport.fetch_certificate_authority_csr + in client._transport._wrapped_methods + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["certificate_authority"] = { - "name": "name_value", - "type_": 1, - "tier": 1, - "config": { - "subject_config": { - "subject": { - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "common_name": "common_name_value", - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "reusable_config": { - "reusable_config": "reusable_config_value", - "reusable_config_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": { - "is_ca": {"value": True}, - "max_issuer_path_length": {"value": 541}, - }, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "additional_extensions": {}, - }, - }, - "public_key": {"type_": 1, "key": b"key_blob"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "key_spec": { - "cloud_kms_key_version": "cloud_kms_key_version_value", - "algorithm": 1, - }, - "certificate_policy": { - "allowed_config_list": {"allowed_config_values": {}}, - "overwrite_config_values": {}, - "allowed_locations_and_organizations": {}, - "allowed_common_names": [ - "allowed_common_names_value1", - "allowed_common_names_value2", - ], - "allowed_sans": { - "allowed_dns_names": [ - "allowed_dns_names_value1", - "allowed_dns_names_value2", - ], - "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], - "allowed_email_addresses": [ - "allowed_email_addresses_value1", - "allowed_email_addresses_value2", - ], - "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], - "allow_globbing_dns_wildcards": True, - "allow_custom_sans": True, - }, - "maximum_lifetime": {}, - "allowed_issuance_modes": { - "allow_csr_based_issuance": True, - "allow_config_based_issuance": True, - }, - }, - "issuing_options": { - "include_ca_cert_url": True, - "include_crl_access_url": True, - }, - "subordinate_config": { - "certificate_authority": "certificate_authority_value", - "pem_issuer_chain": { - "pem_certificates": [ - "pem_certificates_value1", - "pem_certificates_value2", - ] - }, - }, - "state": 1, - "pem_ca_certificates": [ - "pem_ca_certificates_value1", - "pem_ca_certificates_value2", - ], - "ca_certificate_descriptions": [ - { - "subject_description": { - "subject": {}, - "common_name": "common_name_value", - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {"seconds": 751, "nanos": 543}, - "not_after_time": {}, - }, - "config_values": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.fetch_certificate_authority_csr + ] = mock_rpc + + request = {} + client.fetch_certificate_authority_csr(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_certificate_authority_csr(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_certificate_authority_csr_rest_required_fields( + request_type=service.FetchCertificateAuthorityCsrRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_certificate_authority_csr._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() + ).fetch_certificate_authority_csr._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse() + # 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, } - ], - "gcs_bucket": "gcs_bucket_value", - "access_urls": { - "ca_certificate_access_url": "ca_certificate_access_url_value", - "crl_access_url": "crl_access_url_value", - }, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.fetch_certificate_authority_csr(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_certificate_authority_csr_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.fetch_certificate_authority_csr._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_fetch_certificate_authority_csr_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = service.FetchCertificateAuthorityCsrResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 + # Convert return value to protobuf type + return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.fetch_certificate_authority_csr(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch" + % client.transport._host, + args[1], + ) + + +def test_fetch_certificate_authority_csr_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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.fetch_certificate_authority_csr( + service.FetchCertificateAuthorityCsrRequest(), + name="name_value", + ) + + +def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_certificate_authority + ] = mock_rpc + + request = {} + client.get_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_certificate_authority_rest_required_fields( + request_type=service.GetCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._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_certificate_authority._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority() + # 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 + + # Convert return value to protobuf type + return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = resources.CertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 + # Convert return value to protobuf type + return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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_certificate_authority( + service.GetCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_list_certificate_authorities_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_certificate_authorities + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_certificate_authorities + ] = mock_rpc + + request = {} + client.list_certificate_authorities(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_certificate_authorities(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_certificate_authorities_rest_required_fields( + request_type=service.ListCertificateAuthoritiesRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_authorities._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() + ).list_certificate_authorities._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + 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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse() + # 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 + + # Convert return value to protobuf type + return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_authorities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_authorities_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_authorities._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_certificate_authorities_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = service.ListCertificateAuthoritiesResponse() + + # 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", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_authorities(**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/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_authorities_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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.list_certificate_authorities( + service.ListCertificateAuthoritiesRequest(), + parent="parent_value", + ) + + +def test_list_certificate_authorities_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + next_page_token="abc", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[], + next_page_token="def", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + ], + next_page_token="ghi", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateAuthoritiesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_certificate_authorities(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateAuthority) for i in results) + + pages = list(client.list_certificate_authorities(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_restore_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restore_certificate_authority + ] = mock_rpc + + request = {} + client.restore_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restore_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_certificate_authority_rest_required_fields( + request_type=service.RestoreCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_certificate_authority._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() + ).restore_certificate_authority._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.restore_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_restore_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.restore_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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.restore_certificate_authority( + service.RestoreCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_schedule_delete_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.schedule_delete_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.schedule_delete_certificate_authority + ] = mock_rpc + + request = {} + client.schedule_delete_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.schedule_delete_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_schedule_delete_certificate_authority_rest_required_fields( + request_type=service.ScheduleDeleteCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).schedule_delete_certificate_authority._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() + ).schedule_delete_certificate_authority._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.schedule_delete_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_schedule_delete_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.schedule_delete_certificate_authority._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_schedule_delete_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.schedule_delete_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete" + % client.transport._host, + args[1], + ) + + +def test_schedule_delete_certificate_authority_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + 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.schedule_delete_certificate_authority( + service.ScheduleDeleteCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_update_certificate_authority_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_certificate_authority + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_certificate_authority + ] = mock_rpc + + request = {} + client.update_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_certificate_authority(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_certificate_authority_rest_required_fields( + request_type=service.UpdateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_authority._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_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateAuthority", + "updateMask", + ) + ) + ) + + +def test_update_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_authority=resources.CertificateAuthority(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_authority(**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/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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_certificate_authority( + service.UpdateCertificateAuthorityRequest(), + certificate_authority=resources.CertificateAuthority(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_certificate_revocation_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_certificate_revocation_list + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_certificate_revocation_list + ] = mock_rpc + + request = {} + client.get_certificate_revocation_list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_certificate_revocation_list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_certificate_revocation_list_rest_required_fields( + request_type=service.GetCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_revocation_list._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_certificate_revocation_list._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList() + # 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 + + # Convert return value to protobuf type + return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_revocation_list._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = resources.CertificateRevocationList() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + + # 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 + # Convert return value to protobuf type + return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_revocation_list(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_revocation_list_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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_certificate_revocation_list( + service.GetCertificateRevocationListRequest(), + name="name_value", + ) + + +def test_list_certificate_revocation_lists_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_certificate_revocation_lists + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_certificate_revocation_lists + ] = mock_rpc + + request = {} + client.list_certificate_revocation_lists(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_certificate_revocation_lists(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_certificate_revocation_lists_rest_required_fields( + request_type=service.ListCertificateRevocationListsRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_revocation_lists._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() + ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + 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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse() + # 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 + + # Convert return value to protobuf type + return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_revocation_lists(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_revocation_lists_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_certificate_revocation_lists._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_certificate_revocation_lists_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = service.ListCertificateRevocationListsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListCertificateRevocationListsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_revocation_lists(**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/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_revocation_lists_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + 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.list_certificate_revocation_lists( + service.ListCertificateRevocationListsRequest(), + parent="parent_value", + ) + + +def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + next_page_token="abc", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[], + next_page_token="def", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + ], + next_page_token="ghi", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateRevocationListsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + pager = client.list_certificate_revocation_lists(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateRevocationList) for i in results) + + pages = list( + client.list_certificate_revocation_lists(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_certificate_revocation_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_certificate_revocation_list + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_certificate_revocation_list + ] = mock_rpc + + request = {} + client.update_certificate_revocation_list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_certificate_revocation_list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_certificate_revocation_list_rest_required_fields( + request_type=service.UpdateCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_revocation_list._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_certificate_revocation_list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_certificate_revocation_list._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateRevocationList", + "updateMask", + ) + ) + ) + + +def test_update_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_revocation_list=resources.CertificateRevocationList( + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_revocation_list(**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/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_revocation_list_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + 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_certificate_revocation_list( + service.UpdateCertificateRevocationListRequest(), + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_reusable_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_reusable_config in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_reusable_config + ] = mock_rpc + + request = {} + client.get_reusable_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_reusable_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_reusable_config_rest_required_fields( + request_type=service.GetReusableConfigRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_reusable_config._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_reusable_config._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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ReusableConfig() + # 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 + + # Convert return value to protobuf type + return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_reusable_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_reusable_config_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_reusable_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_reusable_config_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = resources.ReusableConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reusableConfigs/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 + # Convert return value to protobuf type + return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_reusable_config(**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/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_reusable_config_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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_reusable_config( + service.GetReusableConfigRequest(), + name="name_value", + ) + + +def test_list_reusable_configs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_reusable_configs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_reusable_configs + ] = mock_rpc + + request = {} + client.list_reusable_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_reusable_configs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_reusable_configs_rest_required_fields( + request_type=service.ListReusableConfigsRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_reusable_configs._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() + ).list_reusable_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + 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 = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListReusableConfigsResponse() + # 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 + + # Convert return value to protobuf type + return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_reusable_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_reusable_configs_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_reusable_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_reusable_configs_rest_flattened(): + client = CertificateAuthorityServiceClient( + 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 = service.ListReusableConfigsResponse() + + # 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", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_reusable_configs(**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/v1beta1/{parent=projects/*/locations/*}/reusableConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_reusable_configs_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + 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.list_reusable_configs( + service.ListReusableConfigsRequest(), + parent="parent_value", + ) + + +def test_list_reusable_configs_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + resources.ReusableConfig(), + resources.ReusableConfig(), + ], + next_page_token="abc", + ), + service.ListReusableConfigsResponse( + reusable_configs=[], + next_page_token="def", + ), + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + ], + next_page_token="ghi", + ), + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + resources.ReusableConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListReusableConfigsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_reusable_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ReusableConfig) for i in results) + + pages = list(client.list_reusable_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CertificateAuthorityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.create_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + call.return_value = resources.Certificate() + client.get_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificates_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificates), "__call__" + ) as call: + call.return_value = service.ListCertificatesResponse() + client.list_certificates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.revoke_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate), "__call__" + ) as call: + call.return_value = resources.Certificate() + client.update_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_activate_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.activate_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_disable_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enable_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.enable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_certificate_authority_csr_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + call.return_value = service.FetchCertificateAuthorityCsrResponse() + client.fetch_certificate_authority_csr(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + call.return_value = resources.CertificateAuthority() + client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_authorities_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + call.return_value = service.ListCertificateAuthoritiesResponse() + client.list_certificate_authorities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_schedule_delete_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.schedule_delete_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.schedule_delete_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ScheduleDeleteCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_authority_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() + + assert args[0] == request_msg + - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCertificateAuthorityRequest.meta.fields[ - "certificate_authority" - ] +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_revocation_list_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + call.return_value = resources.CertificateRevocationList() + client.get_certificate_revocation_list(request=None) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + assert args[0] == request_msg - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_revocation_lists_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_authority" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + call.return_value = service.ListCertificateRevocationListsResponse() + client.list_certificate_revocation_lists(request=None) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_authority"][field])): - del request_init["certificate_authority"][field][i][subfield] - else: - del request_init["certificate_authority"][field][subfield] - request = request_type(**request_init) + assert args[0] == request_msg - # 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 = operations_pb2.Operation(name="operations/spam") - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_revocation_list_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_certificate_authority(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_certificate_revocation_list(request=None) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() + assert args[0] == request_msg -def test_create_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_reusable_config_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_reusable_config), "__call__" + ) as call: + call.return_value = resources.ReusableConfig() + client.get_reusable_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetReusableConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_reusable_configs_empty_call_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_reusable_configs), "__call__" + ) as call: + call.return_value = service.ListReusableConfigsResponse() + client.list_reusable_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListReusableConfigsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CertificateAuthorityServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) ) + await client.create_certificate(request=None) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() - # Ensure method has been cached - assert ( - client._transport.create_certificate_authority - in client._transport._wrapped_methods + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) ) + await client.get_certificate(request=None) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificates_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - client._transport._wrapped_methods[ - client._transport.create_certificate_authority - ] = mock_rpc + await client.list_certificates(request=None) - request = {} - client.create_certificate_authority(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_revoke_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.revoke_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ) + ) + await client.update_certificate(request=None) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() - client.create_certificate_authority(request) + assert args[0] == request_msg - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_activate_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_create_certificate_authority_rest_required_fields( - request_type=service.CreateCertificateAuthorityRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.activate_certificate_authority(request=None) - request_init = {} - request_init["parent"] = "" - request_init["certificate_authority_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() - # verify fields with default values are dropped - assert "certificateAuthorityId" not in jsonified_request + assert args[0] == request_msg - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "certificateAuthorityId" in jsonified_request - assert ( - jsonified_request["certificateAuthorityId"] - == request_init["certificate_authority_id"] +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - jsonified_request["parent"] = "parent_value" - jsonified_request["certificateAuthorityId"] = "certificate_authority_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_certificate_authority._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "certificate_authority_id", - "request_id", + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - ) - jsonified_request.update(unset_fields) + await client.create_certificate_authority(request=None) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "certificateAuthorityId" in jsonified_request - assert ( - jsonified_request["certificateAuthorityId"] == "certificate_authority_id_value" - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + assert args[0] == request_msg - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_disable_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.disable_certificate_authority(request=None) - response = client.create_certificate_authority(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() - expected_params = [ - ( - "certificateAuthorityId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert args[0] == request_msg -def test_create_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_enable_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - unset_fields = transport.create_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "certificateAuthorityId", - "requestId", - ) - ) - & set( - ( - "parent", - "certificateAuthorityId", - "certificateAuthority", - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - ) + await client.enable_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), - ) - client = CertificateAuthorityServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_create_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_create_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCertificateAuthorityRequest.pb( - service.CreateCertificateAuthorityRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + assert args[0] == request_msg - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) - request = service.CreateCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_fetch_certificate_authority_csr_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - client.create_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", + ) ) + await client.fetch_certificate_authority_csr(request=None) - pre.assert_called_once() - post.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() + assert args[0] == request_msg -def test_create_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.CreateCertificateAuthorityRequest -): - client = CertificateAuthorityServiceClient( - 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) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # 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_certificate_authority(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CertificateAuthority.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) + ) + await client.get_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() -def test_create_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert args[0] == request_msg - # 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 = operations_pb2.Operation(name="operations/spam") - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificate_authorities_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - certificate_authority=resources.CertificateAuthority(name="name_value"), - certificate_authority_id="certificate_authority_id_value", + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + await client.list_certificate_authorities(request=None) - client.create_certificate_authority(**mock_args) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() - # 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/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" - % client.transport._host, - args[1], - ) + assert args[0] == request_msg -def test_create_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_certificate_authority( - service.CreateCertificateAuthorityRequest(), - parent="parent_value", - certificate_authority=resources.CertificateAuthority(name="name_value"), - certificate_authority_id="certificate_authority_id_value", + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.restore_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCertificateAuthorityRequest() -def test_create_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - service.DisableCertificateAuthorityRequest, - dict, - ], -) -def test_disable_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_schedule_delete_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.disable_certificate_authority(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.schedule_delete_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.schedule_delete_certificate_authority(request=None) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ScheduleDeleteCertificateAuthorityRequest() + assert args[0] == request_msg -def test_disable_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_authority_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # Ensure method has been cached - assert ( - client._transport.disable_certificate_authority - in client._transport._wrapped_methods + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.update_certificate_authority(request=None) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.disable_certificate_authority - ] = mock_rpc + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() - request = {} - client.disable_certificate_authority(request) + assert args[0] == request_msg - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_certificate_revocation_list_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - client.disable_certificate_authority(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + ) + ) + await client.get_certificate_revocation_list(request=None) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() + assert args[0] == request_msg -def test_disable_certificate_authority_rest_required_fields( - request_type=service.DisableCertificateAuthorityRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - 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, use_integers_for_enums=False) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_certificate_revocation_lists_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).disable_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_certificate_revocation_lists(request=None) - jsonified_request["name"] = "name_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).disable_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert args[0] == request_msg - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_certificate_revocation_list_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_certificate_revocation_list(request=None) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + assert args[0] == request_msg - response = client.disable_certificate_authority(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_reusable_config_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_reusable_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ReusableConfig( + name="name_value", + description="description_value", + ) + ) + await client.get_reusable_config(request=None) -def test_disable_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetReusableConfigRequest() - unset_fields = transport.disable_certificate_authority._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CertificateAuthorityServiceRestInterceptor(), +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_reusable_configs_empty_call_grpc_asyncio(): + client = CertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - client = CertificateAuthorityServiceClient(transport=transport) + + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_disable_certificate_authority", - ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_disable_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DisableCertificateAuthorityRequest.pb( - service.DisableCertificateAuthorityRequest() + type(client.transport.list_reusable_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListReusableConfigsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + await client.list_reusable_configs(request=None) - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListReusableConfigsRequest() - request = service.DisableCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + assert args[0] == request_msg - client.disable_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() +def test_transport_kind_rest(): + transport = CertificateAuthorityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" -def test_disable_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.DisableCertificateAuthorityRequest +def test_create_certificate_rest_bad_request( + request_type=service.CreateCertificateRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } request = request_type(**request_init) @@ -13247,241 +14470,239 @@ def test_disable_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.disable_certificate_authority(request) + client.create_certificate(request) -def test_disable_certificate_authority_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateRequest, + dict, + ], +) +def test_create_certificate_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.disable_certificate_authority(**mock_args) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # 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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable" - % client.transport._host, - args[1], - ) + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCertificateRequest.meta.fields["certificate"] + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] -def test_disable_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.disable_certificate_authority( - service.DisableCertificateAuthorityRequest(), - name="name_value", - ) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -def test_disable_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["certificate"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - service.EnableCertificateAuthorityRequest, - dict, - ], -) -def test_enable_certificate_authority_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate"][field])): + del request_init["certificate"][field][i][subfield] + else: + del request_init["certificate"][field][subfield] 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 = operations_pb2.Operation(name="operations/spam") + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_certificate_authority(request) + response = client.create_certificate(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_enable_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.enable_certificate_authority - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.enable_certificate_authority - ] = mock_rpc - - request = {} - client.enable_certificate_authority(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.enable_certificate_authority(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_enable_certificate_authority_rest_required_fields( - request_type=service.EnableCertificateAuthorityRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).enable_certificate_authority._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() - ).enable_certificate_authority._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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.enable_certificate_authority(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_enable_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.enable_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_certificate_authority_rest_interceptors(null_interceptor): +def test_create_certificate_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13489,23 +14710,20 @@ def test_enable_certificate_authority_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "post_enable_certificate_authority", + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_enable_certificate_authority", + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.EnableCertificateAuthorityRequest.pb( - service.EnableCertificateAuthorityRequest() + pb_message = service.CreateCertificateRequest.pb( + service.CreateCertificateRequest() ) transcode.return_value = { "method": "post", @@ -13514,22 +14732,20 @@ def test_enable_certificate_authority_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value - request = service.EnableCertificateAuthorityRequest() + request = service.CreateCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = resources.Certificate() - client.enable_certificate_authority( + client.create_certificate( request, metadata=[ ("key", "val"), @@ -13541,17 +14757,13 @@ def test_enable_certificate_authority_rest_interceptors(null_interceptor): post.assert_called_once() -def test_enable_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.EnableCertificateAuthorityRequest -): +def test_get_certificate_rest_bad_request(request_type=service.GetCertificateRequest): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" } request = request_type(**request_init) @@ -13560,246 +14772,63 @@ def test_enable_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.enable_certificate_authority(request) - - -def test_enable_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.enable_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable" - % client.transport._host, - args[1], - ) - - -def test_enable_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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.enable_certificate_authority( - service.EnableCertificateAuthorityRequest(), - name="name_value", - ) - - -def test_enable_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.get_certificate(request) @pytest.mark.parametrize( "request_type", [ - service.FetchCertificateAuthorityCsrRequest, + service.GetCertificateRequest, dict, ], ) -def test_fetch_certificate_authority_csr_rest(request_type): +def test_get_certificate_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" } 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 = service.FetchCertificateAuthorityCsrResponse( + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], pem_csr="pem_csr_value", ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_certificate_authority_csr(request) + response = client.get_certificate(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) - assert response.pem_csr == "pem_csr_value" - - -def test_fetch_certificate_authority_csr_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.fetch_certificate_authority_csr - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.fetch_certificate_authority_csr - ] = mock_rpc - - request = {} - client.fetch_certificate_authority_csr(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_certificate_authority_csr(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_fetch_certificate_authority_csr_rest_required_fields( - request_type=service.FetchCertificateAuthorityCsrRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).fetch_certificate_authority_csr._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() - ).fetch_certificate_authority_csr._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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.FetchCertificateAuthorityCsrResponse() - # 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 - - # Convert return value to protobuf type - return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.fetch_certificate_authority_csr(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_fetch_certificate_authority_csr_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.fetch_certificate_authority_csr._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): +def test_get_certificate_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13807,22 +14836,19 @@ def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_fetch_certificate_authority_csr", + transports.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_fetch_certificate_authority_csr", + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.FetchCertificateAuthorityCsrRequest.pb( - service.FetchCertificateAuthorityCsrRequest() - ) + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13830,24 +14856,20 @@ def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - service.FetchCertificateAuthorityCsrResponse.to_json( - service.FetchCertificateAuthorityCsrResponse() - ) - ) + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value - request = service.FetchCertificateAuthorityCsrRequest() + request = service.GetCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.FetchCertificateAuthorityCsrResponse() + post.return_value = resources.Certificate() - client.fetch_certificate_authority_csr( + client.get_certificate( request, metadata=[ ("key", "val"), @@ -13859,17 +14881,15 @@ def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): post.assert_called_once() -def test_fetch_certificate_authority_csr_rest_bad_request( - transport: str = "rest", request_type=service.FetchCertificateAuthorityCsrRequest +def test_list_certificates_rest_bad_request( + request_type=service.ListCertificatesRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } request = request_type(**request_init) @@ -13878,256 +14898,190 @@ def test_fetch_certificate_authority_csr_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_certificate_authority_csr(request) - - -def test_fetch_certificate_authority_csr_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = service.FetchCertificateAuthorityCsrResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 - # Convert return value to protobuf type - return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.fetch_certificate_authority_csr(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch" - % client.transport._host, - args[1], - ) - - -def test_fetch_certificate_authority_csr_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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.fetch_certificate_authority_csr( - service.FetchCertificateAuthorityCsrRequest(), - name="name_value", - ) - - -def test_fetch_certificate_authority_csr_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.list_certificates(request) @pytest.mark.parametrize( "request_type", [ - service.GetCertificateAuthorityRequest, + service.ListCertificatesRequest, dict, ], ) -def test_get_certificate_authority_rest(request_type): +def test_list_certificates_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "parent": "projects/sample1/locations/sample2/certificateAuthorities/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 = resources.CertificateAuthority( - name="name_value", - type_=resources.CertificateAuthority.Type.SELF_SIGNED, - tier=resources.CertificateAuthority.Tier.ENTERPRISE, - state=resources.CertificateAuthority.State.ENABLED, - pem_ca_certificates=["pem_ca_certificates_value"], - gcs_bucket="gcs_bucket_value", + return_value = service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = resources.CertificateAuthority.pb(return_value) + return_value = service.ListCertificatesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_certificate_authority(request) + response = client.list_certificates(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CertificateAuthority) - assert response.name == "name_value" - assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED - assert response.tier == resources.CertificateAuthority.Tier.ENTERPRISE - assert response.state == resources.CertificateAuthority.State.ENABLED - assert response.pem_ca_certificates == ["pem_ca_certificates_value"] - assert response.gcs_bucket == "gcs_bucket_value" - + assert isinstance(response, pagers.ListCertificatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) - # Ensure method has been cached - assert ( - client._transport.get_certificate_authority - in client._transport._wrapped_methods + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificatesRequest.pb( + service.ListCertificatesRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificatesResponse.to_json( + service.ListCertificatesResponse() ) - client._transport._wrapped_methods[ - client._transport.get_certificate_authority - ] = mock_rpc - - request = {} - client.get_certificate_authority(request) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = service.ListCertificatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificatesResponse() - client.get_certificate_authority(request) + client.list_certificates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_get_certificate_authority_rest_required_fields( - request_type=service.GetCertificateAuthorityRequest, +def test_revoke_certificate_rest_bad_request( + request_type=service.RevokeCertificateRequest, ): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_authority._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_certificate_authority._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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CertificateAuthority() - # 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 + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) - response_value = Response() - response_value.status_code = 200 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.revoke_certificate(request) - # Convert return value to protobuf type - return_value = resources.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + service.RevokeCertificateRequest, + dict, + ], +) +def test_revoke_certificate_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.get_certificate_authority(request) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_get_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.revoke_certificate(request) - unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_authority_rest_interceptors(null_interceptor): +def test_revoke_certificate_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14135,21 +15089,20 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_get_certificate_authority", + transports.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_get_certificate_authority", + transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetCertificateAuthorityRequest.pb( - service.GetCertificateAuthorityRequest() + pb_message = service.RevokeCertificateRequest.pb( + service.RevokeCertificateRequest() ) transcode.return_value = { "method": "post", @@ -14158,22 +15111,20 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.CertificateAuthority.to_json( - resources.CertificateAuthority() - ) + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value - request = service.GetCertificateAuthorityRequest() + request = service.RevokeCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CertificateAuthority() + post.return_value = resources.Certificate() - client.get_certificate_authority( + client.revoke_certificate( request, metadata=[ ("key", "val"), @@ -14185,17 +15136,17 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateAuthorityRequest +def test_update_certificate_rest_bad_request( + request_type=service.UpdateCertificateRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } } request = request_type(**request_init) @@ -14204,265 +15155,241 @@ def test_get_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_certificate_authority(request) + client.update_certificate(request) -def test_get_certificate_authority_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRequest, + dict, + ], +) +def test_update_certificate_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = resources.CertificateAuthority() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # 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 - # Convert return value to protobuf type - return_value = resources.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}" - % client.transport._host, - args[1], - ) + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateRequest.meta.fields["certificate"] + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] -def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_certificate_authority( - service.GetCertificateAuthorityRequest(), - name="name_value", - ) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -def test_get_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["certificate"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificateAuthoritiesRequest, - dict, - ], -) -def test_list_certificate_authorities_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate"][field])): + del request_init["certificate"][field][i][subfield] + else: + del request_init["certificate"][field][subfield] 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 = service.ListCertificateAuthoritiesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + return_value = resources.Certificate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_certificate_authorities(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificateAuthoritiesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_certificate_authorities_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_certificate_authorities - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_certificate_authorities - ] = mock_rpc - - request = {} - client.list_certificate_authorities(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_certificate_authorities(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_certificate_authorities_rest_required_fields( - request_type=service.ListCertificateAuthoritiesRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_certificate_authorities._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() - ).list_certificate_authorities._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - 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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListCertificateAuthoritiesResponse() - # 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 - - # Convert return value to protobuf type - return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_certificate_authorities(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_list_certificate_authorities_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_certificate_authorities._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + response = client.update_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificate_authorities_rest_interceptors(null_interceptor): +def test_update_certificate_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14470,21 +15397,20 @@ def test_list_certificate_authorities_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_list_certificate_authorities", + transports.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" ) as post, mock.patch.object( - transports.CertificateAuthorityServiceRestInterceptor, - "pre_list_certificate_authorities", + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListCertificateAuthoritiesRequest.pb( - service.ListCertificateAuthoritiesRequest() + pb_message = service.UpdateCertificateRequest.pb( + service.UpdateCertificateRequest() ) transcode.return_value = { "method": "post", @@ -14493,22 +15419,20 @@ def test_list_certificate_authorities_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service.ListCertificateAuthoritiesResponse.to_json( - service.ListCertificateAuthoritiesResponse() - ) + return_value = resources.Certificate.to_json(resources.Certificate()) + req.return_value.content = return_value - request = service.ListCertificateAuthoritiesRequest() + request = service.UpdateCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListCertificateAuthoritiesResponse() + post.return_value = resources.Certificate() - client.list_certificate_authorities( + client.update_certificate( request, metadata=[ ("key", "val"), @@ -14520,16 +15444,16 @@ def test_list_certificate_authorities_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_certificate_authorities_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificateAuthoritiesRequest +def test_activate_certificate_authority_rest_bad_request( + request_type=service.ActivateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14537,144 +15461,25 @@ def test_list_certificate_authorities_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_certificate_authorities(request) - - -def test_list_certificate_authorities_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = service.ListCertificateAuthoritiesResponse() - - # 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", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.list_certificate_authorities(**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/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" - % client.transport._host, - args[1], - ) - - -def test_list_certificate_authorities_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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.list_certificate_authorities( - service.ListCertificateAuthoritiesRequest(), - parent="parent_value", - ) - - -def test_list_certificate_authorities_rest_pager(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListCertificateAuthoritiesResponse( - certificate_authorities=[ - resources.CertificateAuthority(), - resources.CertificateAuthority(), - resources.CertificateAuthority(), - ], - next_page_token="abc", - ), - service.ListCertificateAuthoritiesResponse( - certificate_authorities=[], - next_page_token="def", - ), - service.ListCertificateAuthoritiesResponse( - certificate_authorities=[ - resources.CertificateAuthority(), - ], - next_page_token="ghi", - ), - service.ListCertificateAuthoritiesResponse( - certificate_authorities=[ - resources.CertificateAuthority(), - resources.CertificateAuthority(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListCertificateAuthoritiesResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_certificate_authorities(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CertificateAuthority) for i in results) - - pages = list(client.list_certificate_authorities(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.activate_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - service.RestoreCertificateAuthorityRequest, + service.ActivateCertificateAuthorityRequest, dict, ], ) -def test_restore_certificate_authority_rest(request_type): +def test_activate_certificate_authority_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -14689,148 +15494,366 @@ def test_restore_certificate_authority_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_certificate_authority(request) + response = client.activate_certificate_authority(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_restore_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + json_return_value = json_format.MessageToJson(return_value) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.restore_certificate_authority - in client._transport._wrapped_methods - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_activate_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_activate_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_activate_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ActivateCertificateAuthorityRequest.pb( + service.ActivateCertificateAuthorityRequest() ) - client._transport._wrapped_methods[ - client._transport.restore_certificate_authority - ] = mock_rpc - - request = {} - client.restore_certificate_authority(request) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = service.ActivateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.restore_certificate_authority(request) + client.activate_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_restore_certificate_authority_rest_required_fields( - request_type=service.RestoreCertificateAuthorityRequest, +def test_create_certificate_authority_rest_bad_request( + request_type=service.CreateCertificateAuthorityRequest, ): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) + client = CertificateAuthorityServiceClient( + 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) - # verify fields with default values are dropped + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_certificate_authority(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).restore_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateAuthorityRequest, + dict, + ], +) +def test_create_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - jsonified_request["name"] = "name_value" + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).restore_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCertificateAuthorityRequest.meta.fields[ + "certificate_authority" + ] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + subfields_not_in_runtime = [] - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_authority" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - response = client.restore_certificate_authority(request) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_authority"][field])): + del request_init["certificate_authority"][field][i][subfield] + else: + del request_init["certificate_authority"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") -def test_restore_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_authority(request) - unset_fields = transport.restore_certificate_authority._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_certificate_authority_rest_interceptors(null_interceptor): +def test_create_certificate_authority_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14838,6 +15861,7 @@ def test_restore_certificate_authority_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -14846,15 +15870,15 @@ def test_restore_certificate_authority_rest_interceptors(null_interceptor): operation.Operation, "_set_result_from_operation" ), mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "post_restore_certificate_authority", + "post_create_certificate_authority", ) as post, mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "pre_restore_certificate_authority", + "pre_create_certificate_authority", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestoreCertificateAuthorityRequest.pb( - service.RestoreCertificateAuthorityRequest() + pb_message = service.CreateCertificateAuthorityRequest.pb( + service.CreateCertificateAuthorityRequest() ) transcode.return_value = { "method": "post", @@ -14863,14 +15887,12 @@ def test_restore_certificate_authority_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = service.RestoreCertificateAuthorityRequest() + request = service.CreateCertificateAuthorityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14878,7 +15900,7 @@ def test_restore_certificate_authority_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.restore_certificate_authority( + client.create_certificate_authority( request, metadata=[ ("key", "val"), @@ -14890,14 +15912,12 @@ def test_restore_certificate_authority_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restore_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.RestoreCertificateAuthorityRequest +def test_disable_certificate_authority_rest_bad_request( + request_type=service.DisableCertificateAuthorityRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" @@ -14909,87 +15929,25 @@ def test_restore_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.restore_certificate_authority(request) - - -def test_restore_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.restore_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore" - % client.transport._host, - args[1], - ) - - -def test_restore_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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.restore_certificate_authority( - service.RestoreCertificateAuthorityRequest(), - name="name_value", - ) - - -def test_restore_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.disable_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - service.ScheduleDeleteCertificateAuthorityRequest, + service.DisableCertificateAuthorityRequest, dict, ], ) -def test_schedule_delete_certificate_authority_rest(request_type): +def test_disable_certificate_authority_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -15004,152 +15962,140 @@ def test_schedule_delete_certificate_authority_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.schedule_delete_certificate_authority(request) + response = client.disable_certificate_authority(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_schedule_delete_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.schedule_delete_certificate_authority - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.schedule_delete_certificate_authority - ] = mock_rpc - - request = {} - client.schedule_delete_certificate_authority(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.schedule_delete_certificate_authority(request) + json_return_value = json_format.MessageToJson(return_value) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_schedule_delete_certificate_authority_rest_required_fields( - request_type=service.ScheduleDeleteCertificateAuthorityRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - 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, use_integers_for_enums=False) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) + client = CertificateAuthorityServiceClient(transport=transport) - # verify fields with default values are dropped + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_disable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_disable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DisableCertificateAuthorityRequest.pb( + service.DisableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).schedule_delete_certificate_authority._get_unset_required_fields( - jsonified_request - ) - jsonified_request.update(unset_fields) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # verify required fields with default values are now present + request = service.DisableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - jsonified_request["name"] = "name_value" + client.disable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).schedule_delete_certificate_authority._get_unset_required_fields( - jsonified_request - ) - jsonified_request.update(unset_fields) + pre.assert_called_once() + post.assert_called_once() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_enable_certificate_authority_rest_bad_request( + request_type=service.EnableCertificateAuthorityRequest, +): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.enable_certificate_authority(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.schedule_delete_certificate_authority(request) +@pytest.mark.parametrize( + "request_type", + [ + service.EnableCertificateAuthorityRequest, + dict, + ], +) +def test_enable_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") -def test_schedule_delete_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enable_certificate_authority(request) - unset_fields = ( - transport.schedule_delete_certificate_authority._get_unset_required_fields({}) - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_schedule_delete_certificate_authority_rest_interceptors(null_interceptor): +def test_enable_certificate_authority_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15157,6 +16103,7 @@ def test_schedule_delete_certificate_authority_rest_interceptors(null_intercepto else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -15165,15 +16112,15 @@ def test_schedule_delete_certificate_authority_rest_interceptors(null_intercepto operation.Operation, "_set_result_from_operation" ), mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "post_schedule_delete_certificate_authority", + "post_enable_certificate_authority", ) as post, mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "pre_schedule_delete_certificate_authority", + "pre_enable_certificate_authority", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ScheduleDeleteCertificateAuthorityRequest.pb( - service.ScheduleDeleteCertificateAuthorityRequest() + pb_message = service.EnableCertificateAuthorityRequest.pb( + service.EnableCertificateAuthorityRequest() ) transcode.return_value = { "method": "post", @@ -15182,14 +16129,12 @@ def test_schedule_delete_certificate_authority_rest_interceptors(null_intercepto "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = service.ScheduleDeleteCertificateAuthorityRequest() + request = service.EnableCertificateAuthorityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15197,7 +16142,7 @@ def test_schedule_delete_certificate_authority_rest_interceptors(null_intercepto pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.schedule_delete_certificate_authority( + client.enable_certificate_authority( request, metadata=[ ("key", "val"), @@ -15209,15 +16154,12 @@ def test_schedule_delete_certificate_authority_rest_interceptors(null_intercepto post.assert_called_once() -def test_schedule_delete_certificate_authority_rest_bad_request( - transport: str = "rest", - request_type=service.ScheduleDeleteCertificateAuthorityRequest, +def test_fetch_certificate_authority_csr_rest_bad_request( + request_type=service.FetchCertificateAuthorityCsrRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" @@ -15229,490 +16171,320 @@ def test_schedule_delete_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.schedule_delete_certificate_authority(request) + client.fetch_certificate_authority_csr(request) -def test_schedule_delete_certificate_authority_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCertificateAuthorityCsrRequest, + dict, + ], +) +def test_fetch_certificate_authority_csr_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + return_value = service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", ) - mock_args.update(sample_request) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.fetch_certificate_authority_csr(request) - client.schedule_delete_certificate_authority(**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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) + assert response.pem_csr == "pem_csr_value" -def test_schedule_delete_certificate_authority_rest_flattened_error( - transport: str = "rest", -): - client = CertificateAuthorityServiceClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) + client = CertificateAuthorityServiceClient(transport=transport) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.schedule_delete_certificate_authority( - service.ScheduleDeleteCertificateAuthorityRequest(), - name="name_value", + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_fetch_certificate_authority_csr", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_fetch_certificate_authority_csr", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCertificateAuthorityCsrRequest.pb( + service.FetchCertificateAuthorityCsrRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.FetchCertificateAuthorityCsrResponse.to_json( + service.FetchCertificateAuthorityCsrResponse() + ) + req.return_value.content = return_value + + request = service.FetchCertificateAuthorityCsrRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCertificateAuthorityCsrResponse() + + client.fetch_certificate_authority_csr( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() -def test_schedule_delete_certificate_authority_rest_error(): +def test_get_certificate_authority_rest_bad_request( + request_type=service.GetCertificateAuthorityRequest, +): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - service.UpdateCertificateAuthorityRequest, + service.GetCertificateAuthorityRequest, dict, ], ) -def test_update_certificate_authority_rest(request_type): +def test_get_certificate_authority_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "certificate_authority": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - } - request_init["certificate_authority"] = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3", - "type_": 1, - "tier": 1, - "config": { - "subject_config": { - "subject": { - "country_code": "country_code_value", - "organization": "organization_value", - "organizational_unit": "organizational_unit_value", - "locality": "locality_value", - "province": "province_value", - "street_address": "street_address_value", - "postal_code": "postal_code_value", - }, - "common_name": "common_name_value", - "subject_alt_name": { - "dns_names": ["dns_names_value1", "dns_names_value2"], - "uris": ["uris_value1", "uris_value2"], - "email_addresses": [ - "email_addresses_value1", - "email_addresses_value2", - ], - "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], - "custom_sans": [ - { - "object_id": {"object_id_path": [1456, 1457]}, - "critical": True, - "value": b"value_blob", - } - ], - }, - }, - "reusable_config": { - "reusable_config": "reusable_config_value", - "reusable_config_values": { - "key_usage": { - "base_key_usage": { - "digital_signature": True, - "content_commitment": True, - "key_encipherment": True, - "data_encipherment": True, - "key_agreement": True, - "cert_sign": True, - "crl_sign": True, - "encipher_only": True, - "decipher_only": True, - }, - "extended_key_usage": { - "server_auth": True, - "client_auth": True, - "code_signing": True, - "email_protection": True, - "time_stamping": True, - "ocsp_signing": True, - }, - "unknown_extended_key_usages": {}, - }, - "ca_options": { - "is_ca": {"value": True}, - "max_issuer_path_length": {"value": 541}, - }, - "policy_ids": {}, - "aia_ocsp_servers": [ - "aia_ocsp_servers_value1", - "aia_ocsp_servers_value2", - ], - "additional_extensions": {}, - }, - }, - "public_key": {"type_": 1, "key": b"key_blob"}, - }, - "lifetime": {"seconds": 751, "nanos": 543}, - "key_spec": { - "cloud_kms_key_version": "cloud_kms_key_version_value", - "algorithm": 1, - }, - "certificate_policy": { - "allowed_config_list": {"allowed_config_values": {}}, - "overwrite_config_values": {}, - "allowed_locations_and_organizations": {}, - "allowed_common_names": [ - "allowed_common_names_value1", - "allowed_common_names_value2", - ], - "allowed_sans": { - "allowed_dns_names": [ - "allowed_dns_names_value1", - "allowed_dns_names_value2", - ], - "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], - "allowed_email_addresses": [ - "allowed_email_addresses_value1", - "allowed_email_addresses_value2", - ], - "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], - "allow_globbing_dns_wildcards": True, - "allow_custom_sans": True, - }, - "maximum_lifetime": {}, - "allowed_issuance_modes": { - "allow_csr_based_issuance": True, - "allow_config_based_issuance": True, - }, - }, - "issuing_options": { - "include_ca_cert_url": True, - "include_crl_access_url": True, - }, - "subordinate_config": { - "certificate_authority": "certificate_authority_value", - "pem_issuer_chain": { - "pem_certificates": [ - "pem_certificates_value1", - "pem_certificates_value2", - ] - }, - }, - "state": 1, - "pem_ca_certificates": [ - "pem_ca_certificates_value1", - "pem_ca_certificates_value2", - ], - "ca_certificate_descriptions": [ - { - "subject_description": { - "subject": {}, - "common_name": "common_name_value", - "subject_alt_name": {}, - "hex_serial_number": "hex_serial_number_value", - "lifetime": {}, - "not_before_time": {"seconds": 751, "nanos": 543}, - "not_after_time": {}, - }, - "config_values": {}, - "public_key": {}, - "subject_key_id": {"key_id": "key_id_value"}, - "authority_key_id": {}, - "crl_distribution_points": [ - "crl_distribution_points_value1", - "crl_distribution_points_value2", - ], - "aia_issuing_certificate_urls": [ - "aia_issuing_certificate_urls_value1", - "aia_issuing_certificate_urls_value2", - ], - "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, - } - ], - "gcs_bucket": "gcs_bucket_value", - "access_urls": { - "ca_certificate_access_url": "ca_certificate_access_url_value", - "crl_access_url": "crl_access_url_value", - }, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCertificateAuthorityRequest.meta.fields[ - "certificate_authority" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "certificate_authority" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["certificate_authority"][field])): - del request_init["certificate_authority"][field][i][subfield] - else: - del request_init["certificate_authority"][field][subfield] + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") + return_value = resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CertificateAuthority.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + # Convert return value to protobuf type + return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_certificate_authority(request) + response = client.get_certificate_authority(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - + assert isinstance(response, resources.CertificateAuthority) + assert response.name == "name_value" + assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED + assert response.tier == resources.CertificateAuthority.Tier.ENTERPRISE + assert response.state == resources.CertificateAuthority.State.ENABLED + assert response.pem_ca_certificates == ["pem_ca_certificates_value"] + assert response.gcs_bucket == "gcs_bucket_value" -def test_update_certificate_authority_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) - # Ensure method has been cached - assert ( - client._transport.update_certificate_authority - in client._transport._wrapped_methods + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateAuthorityRequest.pb( + service.GetCertificateAuthorityRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CertificateAuthority.to_json( + resources.CertificateAuthority() ) - client._transport._wrapped_methods[ - client._transport.update_certificate_authority - ] = mock_rpc - - request = {} - client.update_certificate_authority(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = service.GetCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateAuthority() - client.update_certificate_authority(request) + client.get_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_update_certificate_authority_rest_required_fields( - request_type=service.UpdateCertificateAuthorityRequest, +def test_list_certificate_authorities_rest_bad_request( + request_type=service.ListCertificateAuthoritiesRequest, ): - transport_class = transports.CertificateAuthorityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = CertificateAuthorityServiceClient( + 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) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_certificate_authority._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_certificate_authority._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_certificate_authorities(request) - # verify required fields with non-default values are left alone +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateAuthoritiesRequest, + dict, + ], +) +def test_list_certificate_authorities_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.update_certificate_authority(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_update_certificate_authority_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_authorities(request) - unset_fields = transport.update_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "certificateAuthority", - "updateMask", - ) - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateAuthoritiesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_certificate_authority_rest_interceptors(null_interceptor): +def test_list_certificate_authorities_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15720,23 +16492,22 @@ def test_update_certificate_authority_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "post_update_certificate_authority", + "post_list_certificate_authorities", ) as post, mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "pre_update_certificate_authority", + "pre_list_certificate_authorities", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateCertificateAuthorityRequest.pb( - service.UpdateCertificateAuthorityRequest() + pb_message = service.ListCertificateAuthoritiesRequest.pb( + service.ListCertificateAuthoritiesRequest() ) transcode.return_value = { "method": "post", @@ -15745,22 +16516,22 @@ def test_update_certificate_authority_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + return_value = service.ListCertificateAuthoritiesResponse.to_json( + service.ListCertificateAuthoritiesResponse() ) + req.return_value.content = return_value - request = service.UpdateCertificateAuthorityRequest() + request = service.ListCertificateAuthoritiesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListCertificateAuthoritiesResponse() - client.update_certificate_authority( + client.list_certificate_authorities( request, metadata=[ ("key", "val"), @@ -15772,19 +16543,15 @@ def test_update_certificate_authority_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_certificate_authority_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateAuthorityRequest +def test_restore_certificate_authority_rest_bad_request( + request_type=service.RestoreCertificateAuthorityRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "certificate_authority": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" } request = request_type(**request_init) @@ -15793,258 +16560,173 @@ def test_update_certificate_authority_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_certificate_authority(request) - - -def test_update_certificate_authority_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "certificate_authority": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - } - - # get truthy value for each flattened field - mock_args = dict( - certificate_authority=resources.CertificateAuthority(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.update_certificate_authority(**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/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}" - % client.transport._host, - args[1], - ) - - -def test_update_certificate_authority_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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_certificate_authority( - service.UpdateCertificateAuthorityRequest(), - certificate_authority=resources.CertificateAuthority(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_certificate_authority_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.restore_certificate_authority(request) @pytest.mark.parametrize( "request_type", [ - service.GetCertificateRevocationListRequest, + service.RestoreCertificateAuthorityRequest, dict, ], ) -def test_get_certificate_revocation_list_rest(request_type): +def test_restore_certificate_authority_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = resources.CertificateRevocationList( - name="name_value", - sequence_number=1601, - pem_crl="pem_crl_value", - access_url="access_url_value", - state=resources.CertificateRevocationList.State.ACTIVE, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CertificateRevocationList.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_certificate_revocation_list(request) + response = client.restore_certificate_authority(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CertificateRevocationList) - assert response.name == "name_value" - assert response.sequence_number == 1601 - assert response.pem_crl == "pem_crl_value" - assert response.access_url == "access_url_value" - assert response.state == resources.CertificateRevocationList.State.ACTIVE - - -def test_get_certificate_revocation_list_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_certificate_revocation_list - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_certificate_revocation_list - ] = mock_rpc - - request = {} - client.get_certificate_revocation_list(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_certificate_revocation_list(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + json_return_value = json_format.MessageToJson(return_value) -def test_get_certificate_revocation_list_rest_required_fields( - request_type=service.GetCertificateRevocationListRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) + client = CertificateAuthorityServiceClient(transport=transport) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_revocation_list._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_certificate_revocation_list._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" + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_restore_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_restore_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreCertificateAuthorityRequest.pb( + service.RestoreCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Designate an appropriate value for the returned response. - return_value = resources.CertificateRevocationList() - # 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 + request = service.RestoreCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - response_value = Response() - response_value.status_code = 200 + client.restore_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Convert return value to protobuf type - return_value = resources.CertificateRevocationList.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + pre.assert_called_once() + post.assert_called_once() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_certificate_revocation_list(request) +def test_schedule_delete_certificate_authority_rest_bad_request( + request_type=service.ScheduleDeleteCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.schedule_delete_certificate_authority(request) -def test_get_certificate_revocation_list_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.parametrize( + "request_type", + [ + service.ScheduleDeleteCertificateAuthorityRequest, + dict, + ], +) +def test_schedule_delete_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - unset_fields = transport.get_certificate_revocation_list._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.schedule_delete_certificate_authority(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): +def test_schedule_delete_certificate_authority_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16052,21 +16734,24 @@ def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "post_get_certificate_revocation_list", + "post_schedule_delete_certificate_authority", ) as post, mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "pre_get_certificate_revocation_list", + "pre_schedule_delete_certificate_authority", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetCertificateRevocationListRequest.pb( - service.GetCertificateRevocationListRequest() + pb_message = service.ScheduleDeleteCertificateAuthorityRequest.pb( + service.ScheduleDeleteCertificateAuthorityRequest() ) transcode.return_value = { "method": "post", @@ -16075,22 +16760,20 @@ def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.CertificateRevocationList.to_json( - resources.CertificateRevocationList() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = service.GetCertificateRevocationListRequest() + request = service.ScheduleDeleteCertificateAuthorityRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CertificateRevocationList() + post.return_value = operations_pb2.Operation() - client.get_certificate_revocation_list( + client.schedule_delete_certificate_authority( request, metadata=[ ("key", "val"), @@ -16102,290 +16785,438 @@ def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_certificate_revocation_list_rest_bad_request( - transport: str = "rest", request_type=service.GetCertificateRevocationListRequest +def test_update_certificate_authority_rest_bad_request( + request_type=service.UpdateCertificateAuthorityRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateAuthorityRequest, + dict, + ], +) +def test_update_certificate_authority_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, } - 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_certificate_revocation_list(request) - - -def test_get_certificate_revocation_list_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = resources.CertificateRevocationList() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" - } - - # 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 - # Convert return value to protobuf type - return_value = resources.CertificateRevocationList.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_certificate_revocation_list(**mock_args) + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # 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/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" - % client.transport._host, - args[1], - ) + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCertificateAuthorityRequest.meta.fields[ + "certificate_authority" + ] + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] -def test_get_certificate_revocation_list_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_certificate_revocation_list( - service.GetCertificateRevocationListRequest(), - name="name_value", - ) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -def test_get_certificate_revocation_list_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "certificate_authority" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - service.ListCertificateRevocationListsRequest, - dict, - ], -) -def test_list_certificate_revocation_lists_rest(request_type): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["certificate_authority"][field])): + del request_init["certificate_authority"][field][i][subfield] + else: + del request_init["certificate_authority"][field][subfield] 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 = service.ListCertificateRevocationListsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCertificateRevocationListsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_certificate_revocation_lists(request) + response = client.update_certificate_authority(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCertificateRevocationListsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_certificate_revocation_lists_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_certificate_revocation_lists - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_certificate_revocation_lists - ] = mock_rpc - - request = {} - client.list_certificate_revocation_lists(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_certificate_revocation_lists(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - + json_return_value = json_format.MessageToJson(return_value) -def test_list_certificate_revocation_lists_rest_required_fields( - request_type=service.ListCertificateRevocationListsRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - 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, use_integers_for_enums=False) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) + client = CertificateAuthorityServiceClient(transport=transport) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateAuthorityRequest.pb( + service.UpdateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # verify required fields with default values are now present + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - jsonified_request["parent"] = "parent_value" + request = service.UpdateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", + client.update_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - ) - 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" + pre.assert_called_once() + post.assert_called_once() + +def test_get_certificate_revocation_list_rest_bad_request( + request_type=service.GetCertificateRevocationListRequest, +): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = service.ListCertificateRevocationListsResponse() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_certificate_revocation_list(request) - # Convert return value to protobuf type - return_value = service.ListCertificateRevocationListsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateRevocationListRequest, + dict, + ], +) +def test_get_certificate_revocation_list_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.list_certificate_revocation_lists(request) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_list_certificate_revocation_lists_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_revocation_list(request) - unset_fields = ( - transport.list_certificate_revocation_lists._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateRevocationList) + assert response.name == "name_value" + assert response.sequence_number == 1601 + assert response.pem_crl == "pem_crl_value" + assert response.access_url == "access_url_value" + assert response.state == resources.CertificateRevocationList.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): +def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16393,21 +17224,22 @@ def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, - "post_list_certificate_revocation_lists", + "post_get_certificate_revocation_list", ) as post, mock.patch.object( transports.CertificateAuthorityServiceRestInterceptor, - "pre_list_certificate_revocation_lists", + "pre_get_certificate_revocation_list", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListCertificateRevocationListsRequest.pb( - service.ListCertificateRevocationListsRequest() + pb_message = service.GetCertificateRevocationListRequest.pb( + service.GetCertificateRevocationListRequest() ) transcode.return_value = { "method": "post", @@ -16416,24 +17248,22 @@ def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - service.ListCertificateRevocationListsResponse.to_json( - service.ListCertificateRevocationListsResponse() - ) + return_value = resources.CertificateRevocationList.to_json( + resources.CertificateRevocationList() ) + req.return_value.content = return_value - request = service.ListCertificateRevocationListsRequest() + request = service.GetCertificateRevocationListRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListCertificateRevocationListsResponse() + post.return_value = resources.CertificateRevocationList() - client.list_certificate_revocation_lists( + client.get_certificate_revocation_list( request, metadata=[ ("key", "val"), @@ -16446,13 +17276,11 @@ def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): def test_list_certificate_revocation_lists_rest_bad_request( - transport: str = "rest", request_type=service.ListCertificateRevocationListsRequest + request_type=service.ListCertificateRevocationListsRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" @@ -16464,139 +17292,144 @@ def test_list_certificate_revocation_lists_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.list_certificate_revocation_lists(request) -def test_list_certificate_revocation_lists_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateRevocationListsRequest, + dict, + ], +) +def test_list_certificate_revocation_lists_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/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 = service.ListCertificateRevocationListsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + return_value = service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - mock_args.update(sample_request) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = service.ListCertificateRevocationListsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.list_certificate_revocation_lists(request) - client.list_certificate_revocation_lists(**mock_args) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateRevocationListsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # 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/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists" - % client.transport._host, - args[1], + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(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.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_revocation_lists", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_revocation_lists", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateRevocationListsRequest.pb( + service.ListCertificateRevocationListsRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCertificateRevocationListsResponse.to_json( + service.ListCertificateRevocationListsResponse() + ) + req.return_value.content = return_value -def test_list_certificate_revocation_lists_rest_flattened_error( - transport: str = "rest", -): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + request = service.ListCertificateRevocationListsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateRevocationListsResponse() - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): client.list_certificate_revocation_lists( - service.ListCertificateRevocationListsRequest(), - parent="parent_value", + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() + -def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): +def test_update_certificate_revocation_list_rest_bad_request( + request_type=service.UpdateCertificateRevocationListRequest, +): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListCertificateRevocationListsResponse( - certificate_revocation_lists=[ - resources.CertificateRevocationList(), - resources.CertificateRevocationList(), - resources.CertificateRevocationList(), - ], - next_page_token="abc", - ), - service.ListCertificateRevocationListsResponse( - certificate_revocation_lists=[], - next_page_token="def", - ), - service.ListCertificateRevocationListsResponse( - certificate_revocation_lists=[ - resources.CertificateRevocationList(), - ], - next_page_token="ghi", - ), - service.ListCertificateRevocationListsResponse( - certificate_revocation_lists=[ - resources.CertificateRevocationList(), - resources.CertificateRevocationList(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListCertificateRevocationListsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" } + } + request = request_type(**request_init) - pager = client.list_certificate_revocation_lists(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CertificateRevocationList) for i in results) - - pages = list( - client.list_certificate_revocation_lists(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_certificate_revocation_list(request) @pytest.mark.parametrize( @@ -16606,10 +17439,9 @@ def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): dict, ], ) -def test_update_certificate_revocation_list_rest(request_type): +def test_update_certificate_revocation_list_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -16707,168 +17539,24 @@ def get_message_fields(field): ): del request_init["certificate_revocation_list"][field][i][subfield] else: - del request_init["certificate_revocation_list"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_certificate_revocation_list(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_certificate_revocation_list_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_certificate_revocation_list - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_certificate_revocation_list - ] = mock_rpc - - request = {} - client.update_certificate_revocation_list(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_certificate_revocation_list(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_certificate_revocation_list_rest_required_fields( - request_type=service.UpdateCertificateRevocationListRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_certificate_revocation_list._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_certificate_revocation_list._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.update_certificate_revocation_list(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + del request_init["certificate_revocation_list"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") -def test_update_certificate_revocation_list_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_revocation_list(request) - unset_fields = ( - transport.update_certificate_revocation_list._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "certificateRevocationList", - "updateMask", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -16880,6 +17568,7 @@ def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -16905,12 +17594,10 @@ def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = service.UpdateCertificateRevocationListRequest() metadata = [ @@ -16932,19 +17619,15 @@ def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_certificate_revocation_list_rest_bad_request( - transport: str = "rest", request_type=service.UpdateCertificateRevocationListRequest +def test_get_reusable_config_rest_bad_request( + request_type=service.GetReusableConfigRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "certificate_revocation_list": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" - } + "name": "projects/sample1/locations/sample2/reusableConfigs/sample3" } request = request_type(**request_init) @@ -16953,84 +17636,13 @@ def test_update_certificate_revocation_list_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_certificate_revocation_list(request) - - -def test_update_certificate_revocation_list_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "certificate_revocation_list": { - "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" - } - } - - # get truthy value for each flattened field - mock_args = dict( - certificate_revocation_list=resources.CertificateRevocationList( - 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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.update_certificate_revocation_list(**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/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" - % client.transport._host, - args[1], - ) - - -def test_update_certificate_revocation_list_rest_flattened_error( - transport: str = "rest", -): - client = CertificateAuthorityServiceClient( - 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_certificate_revocation_list( - service.UpdateCertificateRevocationListRequest(), - certificate_revocation_list=resources.CertificateRevocationList( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_certificate_revocation_list_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.get_reusable_config(request) @pytest.mark.parametrize( @@ -17040,10 +17652,9 @@ def test_update_certificate_revocation_list_rest_error(): dict, ], ) -def test_get_reusable_config_rest(request_type): +def test_get_reusable_config_rest_call_success(request_type): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -17061,143 +17672,20 @@ def test_get_reusable_config_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ReusableConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_reusable_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ReusableConfig) - assert response.name == "name_value" - assert response.description == "description_value" - - -def test_get_reusable_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_reusable_config in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.get_reusable_config - ] = mock_rpc - - request = {} - client.get_reusable_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_reusable_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_reusable_config_rest_required_fields( - request_type=service.GetReusableConfigRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_reusable_config._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_reusable_config._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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.ReusableConfig() - # 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 - - # Convert return value to protobuf type - return_value = resources.ReusableConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_reusable_config(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_get_reusable_config_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_reusable_config(request) - unset_fields = transport.get_reusable_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ReusableConfig) + assert response.name == "name_value" + assert response.description == "description_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -17209,6 +17697,7 @@ def test_get_reusable_config_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -17231,12 +17720,10 @@ def test_get_reusable_config_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.ReusableConfig.to_json( - resources.ReusableConfig() - ) + return_value = resources.ReusableConfig.to_json(resources.ReusableConfig()) + req.return_value.content = return_value request = service.GetReusableConfigRequest() metadata = [ @@ -17258,18 +17745,14 @@ def test_get_reusable_config_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_reusable_config_rest_bad_request( - transport: str = "rest", request_type=service.GetReusableConfigRequest +def test_list_reusable_configs_rest_bad_request( + request_type=service.ListReusableConfigsRequest, ): client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/reusableConfigs/sample3" - } + 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. @@ -17277,261 +17760,54 @@ def test_get_reusable_config_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_reusable_config(request) - - -def test_get_reusable_config_rest_flattened(): - client = CertificateAuthorityServiceClient( - 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 = resources.ReusableConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/reusableConfigs/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 - # Convert return value to protobuf type - return_value = resources.ReusableConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_reusable_config(**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/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}" - % client.transport._host, - args[1], - ) - - -def test_get_reusable_config_rest_flattened_error(transport: str = "rest"): - client = CertificateAuthorityServiceClient( - 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_reusable_config( - service.GetReusableConfigRequest(), - name="name_value", - ) - - -def test_get_reusable_config_rest_error(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListReusableConfigsRequest, - dict, - ], -) -def test_list_reusable_configs_rest(request_type): - client = CertificateAuthorityServiceClient( - 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 = service.ListReusableConfigsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListReusableConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - response = client.list_reusable_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListReusableConfigsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_reusable_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_reusable_configs - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_reusable_configs - ] = mock_rpc - - request = {} - client.list_reusable_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_reusable_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_reusable_configs_rest_required_fields( - request_type=service.ListReusableConfigsRequest, -): - transport_class = transports.CertificateAuthorityServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_reusable_configs._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() - ).list_reusable_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - 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 = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListReusableConfigsResponse() - # 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 - - # Convert return value to protobuf type - return_value = service.ListReusableConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_reusable_configs(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + client.list_reusable_configs(request) -def test_list_reusable_configs_rest_unset_required_fields(): - transport = transports.CertificateAuthorityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.parametrize( + "request_type", + [ + service.ListReusableConfigsRequest, + dict, + ], +) +def test_list_reusable_configs_rest_call_success(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - unset_fields = transport.list_reusable_configs._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # 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 = service.ListReusableConfigsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - & set(("parent",)) - ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_reusable_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReusableConfigsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -17543,6 +17819,7 @@ def test_list_reusable_configs_rest_interceptors(null_interceptor): else transports.CertificateAuthorityServiceRestInterceptor(), ) client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -17566,12 +17843,12 @@ def test_list_reusable_configs_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service.ListReusableConfigsResponse.to_json( + return_value = service.ListReusableConfigsResponse.to_json( service.ListReusableConfigsResponse() ) + req.return_value.content = return_value request = service.ListReusableConfigsRequest() metadata = [ @@ -17593,254 +17870,466 @@ def test_list_reusable_configs_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_reusable_configs_rest_bad_request( - transport: str = "rest", request_type=service.ListReusableConfigsRequest -): +def test_initialize_client_w_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_empty_call_rest(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate), "__call__" + ) as call: + client.create_certificate(request=None) - # 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.list_reusable_configs(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateRequest() + assert args[0] == request_msg -def test_list_reusable_configs_rest_flattened(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_empty_call_rest(): client = CertificateAuthorityServiceClient( 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 = service.ListReusableConfigsResponse() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_certificate), "__call__") as call: + client.get_certificate(request=None) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListReusableConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.list_reusable_configs(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificates_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v1beta1/{parent=projects/*/locations/*}/reusableConfigs" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificates), "__call__" + ) as call: + client.list_certificates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificatesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.revoke_certificate), "__call__" + ) as call: + client.revoke_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RevokeCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate), "__call__" + ) as call: + client.update_certificate(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_activate_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.activate_certificate_authority), "__call__" + ) as call: + client.activate_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ActivateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_certificate_authority), "__call__" + ) as call: + client.create_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_disable_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_certificate_authority), "__call__" + ) as call: + client.disable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DisableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enable_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_certificate_authority), "__call__" + ) as call: + client.enable_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_fetch_certificate_authority_csr_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_certificate_authority_csr), "__call__" + ) as call: + client.fetch_certificate_authority_csr(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.FetchCertificateAuthorityCsrRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateAuthorityRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_authorities_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_authorities), "__call__" + ) as call: + client.list_certificate_authorities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateAuthoritiesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_certificate_authority_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_certificate_authority), "__call__" + ) as call: + client.restore_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCertificateAuthorityRequest() -def test_list_reusable_configs_rest_flattened_error(transport: str = "rest"): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_schedule_delete_certificate_authority_empty_call_rest(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_reusable_configs( - service.ListReusableConfigsRequest(), - parent="parent_value", - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.schedule_delete_certificate_authority), "__call__" + ) as call: + client.schedule_delete_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ScheduleDeleteCertificateAuthorityRequest() -def test_list_reusable_configs_rest_pager(transport: str = "rest"): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_authority_empty_call_rest(): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListReusableConfigsResponse( - reusable_configs=[ - resources.ReusableConfig(), - resources.ReusableConfig(), - resources.ReusableConfig(), - ], - next_page_token="abc", - ), - service.ListReusableConfigsResponse( - reusable_configs=[], - next_page_token="def", - ), - service.ListReusableConfigsResponse( - reusable_configs=[ - resources.ReusableConfig(), - ], - next_page_token="ghi", - ), - service.ListReusableConfigsResponse( - reusable_configs=[ - resources.ReusableConfig(), - resources.ReusableConfig(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_authority), "__call__" + ) as call: + client.update_certificate_authority(request=None) - # Wrap the values into proper Response objs - response = tuple( - service.ListReusableConfigsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateAuthorityRequest() - sample_request = {"parent": "projects/sample1/locations/sample2"} + assert args[0] == request_msg - pager = client.list_reusable_configs(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ReusableConfig) for i in results) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_certificate_revocation_list_empty_call_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pages = list(client.list_reusable_configs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_revocation_list), "__call__" + ) as call: + client.get_certificate_revocation_list(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCertificateRevocationListRequest() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert args[0] == request_msg - # It is an error to provide a credentials file and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_certificate_revocation_lists_empty_call_rest(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_certificate_revocation_lists), "__call__" + ) as call: + client.list_certificate_revocation_lists(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCertificateRevocationListsRequest() + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_certificate_revocation_list_empty_call_rest(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CertificateAuthorityServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_certificate_revocation_list), "__call__" + ) as call: + client.update_certificate_revocation_list(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCertificateRevocationListRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_reusable_config_empty_call_rest(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_reusable_config), "__call__" + ) as call: + client.get_reusable_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetReusableConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_reusable_configs_empty_call_rest(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_reusable_configs), "__call__" + ) as call: + client.list_reusable_configs(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - transports.CertificateAuthorityServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListReusableConfigsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( + +def test_certificate_authority_service_rest_lro_client(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -18103,23 +18592,6 @@ def test_certificate_authority_service_http_transport_client_cert_source_for_mtl mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_certificate_authority_service_rest_lro_client(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -18657,36 +19129,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = CertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/README.rst b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/README.rst new file mode 100644 index 000000000000..3e0f2ed64cf5 --- /dev/null +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PrivateCatalogTransport` is the ABC for all transports. +- public child `PrivateCatalogGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PrivateCatalogGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePrivateCatalogRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PrivateCatalogRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/grpc_asyncio.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/grpc_asyncio.py index be13be41ecc1..3359304fff03 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/grpc_asyncio.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -247,6 +248,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -355,25 +359,34 @@ def search_versions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.search_catalogs: gapic_v1.method_async.wrap_method( + self.search_catalogs: self._wrap_method( self.search_catalogs, default_timeout=None, client_info=client_info, ), - self.search_products: gapic_v1.method_async.wrap_method( + self.search_products: self._wrap_method( self.search_products, default_timeout=None, client_info=client_info, ), - self.search_versions: gapic_v1.method_async.wrap_method( + self.search_versions: self._wrap_method( self.search_versions, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PrivateCatalogGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py index b735c2565720..4dc303a03822 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.privatecatalog_v1beta1.types import private_catalog + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePrivateCatalogRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.privatecatalog_v1beta1.types import private_catalog - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PrivateCatalogTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -170,8 +167,8 @@ class PrivateCatalogRestStub: _interceptor: PrivateCatalogRestInterceptor -class PrivateCatalogRestTransport(PrivateCatalogTransport): - """REST backend transport for PrivateCatalog. +class PrivateCatalogRestTransport(_BasePrivateCatalogRestTransport): + """REST backend synchronous transport for PrivateCatalog. ``PrivateCatalog`` allows catalog consumers to retrieve ``Catalog``, ``Product`` and ``Version`` resources under a target resource @@ -201,7 +198,6 @@ class PrivateCatalogRestTransport(PrivateCatalogTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -255,21 +251,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -280,19 +267,33 @@ def __init__( self._interceptor = interceptor or PrivateCatalogRestInterceptor() self._prep_wrapped_messages(client_info) - class _SearchCatalogs(PrivateCatalogRestStub): + class _SearchCatalogs( + _BasePrivateCatalogRestTransport._BaseSearchCatalogs, PrivateCatalogRestStub + ): def __hash__(self): - return hash("SearchCatalogs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivateCatalogRestTransport.SearchCatalogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -321,46 +322,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*}/catalogs:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=organizations/*}/catalogs:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=folders/*}/catalogs:search", - }, - ] + http_options = ( + _BasePrivateCatalogRestTransport._BaseSearchCatalogs._get_http_options() + ) request, metadata = self._interceptor.pre_search_catalogs(request, metadata) - pb_request = private_catalog.SearchCatalogsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivateCatalogRestTransport._BaseSearchCatalogs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivateCatalogRestTransport._BaseSearchCatalogs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivateCatalogRestTransport._SearchCatalogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -376,19 +358,33 @@ def __call__( resp = self._interceptor.post_search_catalogs(resp) return resp - class _SearchProducts(PrivateCatalogRestStub): + class _SearchProducts( + _BasePrivateCatalogRestTransport._BaseSearchProducts, PrivateCatalogRestStub + ): def __hash__(self): - return hash("SearchProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivateCatalogRestTransport.SearchProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -417,46 +413,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*}/products:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=organizations/*}/products:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=folders/*}/products:search", - }, - ] + http_options = ( + _BasePrivateCatalogRestTransport._BaseSearchProducts._get_http_options() + ) request, metadata = self._interceptor.pre_search_products(request, metadata) - pb_request = private_catalog.SearchProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivateCatalogRestTransport._BaseSearchProducts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivateCatalogRestTransport._BaseSearchProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivateCatalogRestTransport._SearchProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -472,21 +449,33 @@ def __call__( resp = self._interceptor.post_search_products(resp) return resp - class _SearchVersions(PrivateCatalogRestStub): + class _SearchVersions( + _BasePrivateCatalogRestTransport._BaseSearchVersions, PrivateCatalogRestStub + ): def __hash__(self): - return hash("SearchVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query": "", - } - - @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 - } + return hash("PrivateCatalogRestTransport.SearchVersions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -515,46 +504,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{resource=projects/*}/versions:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=organizations/*}/versions:search", - }, - { - "method": "get", - "uri": "/v1beta1/{resource=folders/*}/versions:search", - }, - ] + http_options = ( + _BasePrivateCatalogRestTransport._BaseSearchVersions._get_http_options() + ) request, metadata = self._interceptor.pre_search_versions(request, metadata) - pb_request = private_catalog.SearchVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivateCatalogRestTransport._BaseSearchVersions._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivateCatalogRestTransport._BaseSearchVersions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivateCatalogRestTransport._SearchVersions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest_base.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest_base.py new file mode 100644 index 000000000000..e8503dd243f7 --- /dev/null +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/services/private_catalog/transports/rest_base.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.privatecatalog_v1beta1.types import private_catalog + +from .base import DEFAULT_CLIENT_INFO, PrivateCatalogTransport + + +class _BasePrivateCatalogRestTransport(PrivateCatalogTransport): + """Base REST backend transport for PrivateCatalog. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudprivatecatalog.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudprivatecatalog.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseSearchCatalogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/catalogs:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/catalogs:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/catalogs:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = private_catalog.SearchCatalogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivateCatalogRestTransport._BaseSearchCatalogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/products:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/products:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/products:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = private_catalog.SearchProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivateCatalogRestTransport._BaseSearchProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{resource=projects/*}/versions:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=organizations/*}/versions:search", + }, + { + "method": "get", + "uri": "/v1beta1/{resource=folders/*}/versions:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = private_catalog.SearchVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivateCatalogRestTransport._BaseSearchVersions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePrivateCatalogRestTransport",) diff --git a/packages/google-cloud-private-catalog/setup.py b/packages/google-cloud-private-catalog/setup.py index 3b6583ed4400..2d1845691f60 100644 --- a/packages/google-cloud-private-catalog/setup.py +++ b/packages/google-cloud-private-catalog/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py b/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py index e858dc325ab6..cd95bda00f1e 100644 --- a/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py +++ b/packages/google-cloud-private-catalog/tests/unit/gapic/privatecatalog_v1beta1/test_private_catalog.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.privatecatalog_v1beta1.services.private_catalog import ( PrivateCatalogAsyncClient, PrivateCatalogClient, @@ -52,10 +61,24 @@ from google.cloud.privatecatalog_v1beta1.types import private_catalog +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1153,25 +1176,6 @@ def test_search_catalogs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_catalogs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchCatalogsRequest() - - def test_search_catalogs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1239,29 +1243,6 @@ def test_search_catalogs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_catalogs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_catalogs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - private_catalog.SearchCatalogsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchCatalogsRequest() - - @pytest.mark.asyncio async def test_search_catalogs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1270,7 +1251,7 @@ async def test_search_catalogs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1309,7 +1290,7 @@ async def test_search_catalogs_async( transport: str = "grpc_asyncio", request_type=private_catalog.SearchCatalogsRequest ): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1375,7 +1356,7 @@ def test_search_catalogs_field_headers(): @pytest.mark.asyncio async def test_search_catalogs_field_headers_async(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1502,7 +1483,7 @@ def test_search_catalogs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_catalogs_async_pager(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1552,7 +1533,7 @@ async def test_search_catalogs_async_pager(): @pytest.mark.asyncio async def test_search_catalogs_async_pages(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1634,25 +1615,6 @@ def test_search_products(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchProductsRequest() - - def test_search_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1720,29 +1682,6 @@ def test_search_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - private_catalog.SearchProductsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchProductsRequest() - - @pytest.mark.asyncio async def test_search_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1751,7 +1690,7 @@ async def test_search_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1790,7 +1729,7 @@ async def test_search_products_async( transport: str = "grpc_asyncio", request_type=private_catalog.SearchProductsRequest ): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1856,7 +1795,7 @@ def test_search_products_field_headers(): @pytest.mark.asyncio async def test_search_products_field_headers_async(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1983,7 +1922,7 @@ def test_search_products_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_products_async_pager(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2033,7 +1972,7 @@ async def test_search_products_async_pager(): @pytest.mark.asyncio async def test_search_products_async_pages(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2115,25 +2054,6 @@ def test_search_versions(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_versions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_versions), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchVersionsRequest() - - def test_search_versions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2201,29 +2121,6 @@ def test_search_versions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_versions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_versions), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - private_catalog.SearchVersionsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == private_catalog.SearchVersionsRequest() - - @pytest.mark.asyncio async def test_search_versions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2232,7 +2129,7 @@ async def test_search_versions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2271,7 +2168,7 @@ async def test_search_versions_async( transport: str = "grpc_asyncio", request_type=private_catalog.SearchVersionsRequest ): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2337,7 +2234,7 @@ def test_search_versions_field_headers(): @pytest.mark.asyncio async def test_search_versions_field_headers_async(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2464,7 +2361,7 @@ def test_search_versions_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_versions_async_pager(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2514,7 +2411,7 @@ async def test_search_versions_async_pager(): @pytest.mark.asyncio async def test_search_versions_async_pages(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2560,46 +2457,6 @@ async def test_search_versions_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - private_catalog.SearchCatalogsRequest, - dict, - ], -) -def test_search_catalogs_rest(request_type): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = private_catalog.SearchCatalogsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = private_catalog.SearchCatalogsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_catalogs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchCatalogsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_catalogs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2736,87 +2593,6 @@ def test_search_catalogs_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_catalogs_rest_interceptors(null_interceptor): - transport = transports.PrivateCatalogRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivateCatalogRestInterceptor(), - ) - client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_catalogs" - ) as post, mock.patch.object( - transports.PrivateCatalogRestInterceptor, "pre_search_catalogs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = private_catalog.SearchCatalogsRequest.pb( - private_catalog.SearchCatalogsRequest() - ) - 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 = private_catalog.SearchCatalogsResponse.to_json( - private_catalog.SearchCatalogsResponse() - ) - - request = private_catalog.SearchCatalogsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = private_catalog.SearchCatalogsResponse() - - client.search_catalogs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_catalogs_rest_bad_request( - transport: str = "rest", request_type=private_catalog.SearchCatalogsRequest -): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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.search_catalogs(request) - - def test_search_catalogs_rest_pager(transport: str = "rest"): client = PrivateCatalogClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2880,46 +2656,6 @@ def test_search_catalogs_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - private_catalog.SearchProductsRequest, - dict, - ], -) -def test_search_products_rest(request_type): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = private_catalog.SearchProductsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = private_catalog.SearchProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_products(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchProductsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3056,87 +2792,6 @@ def test_search_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_products_rest_interceptors(null_interceptor): - transport = transports.PrivateCatalogRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivateCatalogRestInterceptor(), - ) - client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_products" - ) as post, mock.patch.object( - transports.PrivateCatalogRestInterceptor, "pre_search_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = private_catalog.SearchProductsRequest.pb( - private_catalog.SearchProductsRequest() - ) - 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 = private_catalog.SearchProductsResponse.to_json( - private_catalog.SearchProductsResponse() - ) - - request = private_catalog.SearchProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = private_catalog.SearchProductsResponse() - - client.search_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_products_rest_bad_request( - transport: str = "rest", request_type=private_catalog.SearchProductsRequest -): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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.search_products(request) - - def test_search_products_rest_pager(transport: str = "rest"): client = PrivateCatalogClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3200,46 +2855,6 @@ def test_search_products_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - private_catalog.SearchVersionsRequest, - dict, - ], -) -def test_search_versions_rest(request_type): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = private_catalog.SearchVersionsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = private_catalog.SearchVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchVersionsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_versions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3371,27 +2986,666 @@ def test_search_versions_rest_required_fields( assert expected_params == actual_params -def test_search_versions_rest_unset_required_fields(): - transport = transports.PrivateCatalogRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_search_versions_rest_unset_required_fields(): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set( + ( + "resource", + "query", + ) + ) + ) + + +def test_search_versions_rest_pager(transport: str = "rest"): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + private_catalog.Version(), + private_catalog.Version(), + ], + next_page_token="abc", + ), + private_catalog.SearchVersionsResponse( + versions=[], + next_page_token="def", + ), + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + ], + next_page_token="ghi", + ), + private_catalog.SearchVersionsResponse( + versions=[ + private_catalog.Version(), + private_catalog.Version(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + private_catalog.SearchVersionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"resource": "projects/sample1"} + + pager = client.search_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, private_catalog.Version) for i in results) + + pages = list(client.search_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PrivateCatalogClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PrivateCatalogClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PrivateCatalogClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PrivateCatalogClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PrivateCatalogClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PrivateCatalogGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PrivateCatalogGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivateCatalogGrpcTransport, + transports.PrivateCatalogGrpcAsyncIOTransport, + transports.PrivateCatalogRestTransport, + ], +) +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_transport_kind_grpc(): + transport = PrivateCatalogClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_catalogs_empty_call_grpc(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_catalogs), "__call__") as call: + call.return_value = private_catalog.SearchCatalogsResponse() + client.search_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_products_empty_call_grpc(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_products), "__call__") as call: + call.return_value = private_catalog.SearchProductsResponse() + client.search_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_versions_empty_call_grpc(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_versions), "__call__") as call: + call.return_value = private_catalog.SearchVersionsResponse() + client.search_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PrivateCatalogAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PrivateCatalogAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_catalogs_empty_call_grpc_asyncio(): + client = PrivateCatalogAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_catalogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + private_catalog.SearchCatalogsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_products_empty_call_grpc_asyncio(): + client = PrivateCatalogAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + private_catalog.SearchProductsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_versions_empty_call_grpc_asyncio(): + client = PrivateCatalogAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + private_catalog.SearchVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PrivateCatalogClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_catalogs_rest_bad_request( + request_type=private_catalog.SearchCatalogsRequest, +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_catalogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + private_catalog.SearchCatalogsRequest, + dict, + ], +) +def test_search_catalogs_rest_call_success(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = private_catalog.SearchCatalogsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = private_catalog.SearchCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchCatalogsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_catalogs_rest_interceptors(null_interceptor): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivateCatalogRestInterceptor(), + ) + client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_catalogs" + ) as post, mock.patch.object( + transports.PrivateCatalogRestInterceptor, "pre_search_catalogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = private_catalog.SearchCatalogsRequest.pb( + private_catalog.SearchCatalogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = private_catalog.SearchCatalogsResponse.to_json( + private_catalog.SearchCatalogsResponse() + ) + req.return_value.content = return_value + + request = private_catalog.SearchCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = private_catalog.SearchCatalogsResponse() + + client.search_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_products_rest_bad_request( + request_type=private_catalog.SearchProductsRequest, +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + private_catalog.SearchProductsRequest, + dict, + ], +) +def test_search_products_rest_call_success(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = private_catalog.SearchProductsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = private_catalog.SearchProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProductsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_products_rest_interceptors(null_interceptor): + transport = transports.PrivateCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivateCatalogRestInterceptor(), + ) + client = PrivateCatalogClient(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.PrivateCatalogRestInterceptor, "post_search_products" + ) as post, mock.patch.object( + transports.PrivateCatalogRestInterceptor, "pre_search_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = private_catalog.SearchProductsRequest.pb( + private_catalog.SearchProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = private_catalog.SearchProductsResponse.to_json( + private_catalog.SearchProductsResponse() + ) + req.return_value.content = return_value + + request = private_catalog.SearchProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = private_catalog.SearchProductsResponse() + + client.search_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_versions_rest_bad_request( + request_type=private_catalog.SearchVersionsRequest, +): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_versions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + private_catalog.SearchVersionsRequest, + dict, + ], +) +def test_search_versions_rest_call_success(request_type): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - unset_fields = transport.search_versions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - "query", - ) - ) - & set( - ( - "resource", - "query", - ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = private_catalog.SearchVersionsResponse( + next_page_token="next_page_token_value", ) - ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = private_catalog.SearchVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchVersionsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -3403,6 +3657,7 @@ def test_search_versions_rest_interceptors(null_interceptor): else transports.PrivateCatalogRestInterceptor(), ) client = PrivateCatalogClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -3424,12 +3679,12 @@ def test_search_versions_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = private_catalog.SearchVersionsResponse.to_json( + return_value = private_catalog.SearchVersionsResponse.to_json( private_catalog.SearchVersionsResponse() ) + req.return_value.content = return_value request = private_catalog.SearchVersionsRequest() metadata = [ @@ -3451,197 +3706,71 @@ def test_search_versions_rest_interceptors(null_interceptor): post.assert_called_once() -def test_search_versions_rest_bad_request( - transport: str = "rest", request_type=private_catalog.SearchVersionsRequest -): +def test_initialize_client_w_rest(): client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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.search_versions(request) + assert client is not None -def test_search_versions_rest_pager(transport: str = "rest"): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_catalogs_empty_call_rest(): client = PrivateCatalogClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - private_catalog.SearchVersionsResponse( - versions=[ - private_catalog.Version(), - private_catalog.Version(), - private_catalog.Version(), - ], - next_page_token="abc", - ), - private_catalog.SearchVersionsResponse( - versions=[], - next_page_token="def", - ), - private_catalog.SearchVersionsResponse( - versions=[ - private_catalog.Version(), - ], - next_page_token="ghi", - ), - private_catalog.SearchVersionsResponse( - versions=[ - private_catalog.Version(), - private_catalog.Version(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - private_catalog.SearchVersionsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"resource": "projects/sample1"} - - pager = client.search_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, private_catalog.Version) for i in results) - - pages = list(client.search_versions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PrivateCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_catalogs), "__call__") as call: + client.search_catalogs(request=None) - # It is an error to provide a credentials file and a transport instance. - transport = transports.PrivateCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PrivateCatalogClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchCatalogsRequest() - # It is an error to provide an api_key and a transport instance. - transport = transports.PrivateCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PrivateCatalogClient( - client_options=options, - transport=transport, - ) + assert args[0] == request_msg - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PrivateCatalogClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.PrivateCatalogGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_products_empty_call_rest(): + client = PrivateCatalogClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = PrivateCatalogClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_products), "__call__") as call: + client.search_products(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PrivateCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PrivateCatalogClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchProductsRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PrivateCatalogGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.PrivateCatalogGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_versions_empty_call_rest(): + client = PrivateCatalogClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_versions), "__call__") as call: + client.search_versions(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivateCatalogGrpcTransport, - transports.PrivateCatalogGrpcAsyncIOTransport, - transports.PrivateCatalogRestTransport, - ], -) -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() - + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = private_catalog.SearchVersionsRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PrivateCatalogClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name + assert args[0] == request_msg def test_transport_grpc_default(): @@ -4267,36 +4396,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PrivateCatalogAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PrivateCatalogClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PrivateCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/async_client.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/async_client.py index 088d702fea61..e80076be6cf8 100644 --- a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/async_client.py +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/async_client.py @@ -1918,11 +1918,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1975,11 +1971,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2036,11 +2028,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2090,11 +2078,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -2147,11 +2131,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/client.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/client.py index 8092e7274f66..bb6eddac558f 100644 --- a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/client.py +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/client.py @@ -2339,11 +2339,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2396,11 +2392,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2457,11 +2449,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2511,11 +2499,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -2568,11 +2552,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/README.rst b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/README.rst new file mode 100644 index 000000000000..7ab2494d17da --- /dev/null +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PrivilegedAccessManagerTransport` is the ABC for all transports. +- public child `PrivilegedAccessManagerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PrivilegedAccessManagerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePrivilegedAccessManagerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PrivilegedAccessManagerRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/base.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/base.py index e1929c15766b..7a29367b6c23 100644 --- a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/base.py +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/base.py @@ -200,6 +200,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/grpc_asyncio.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/grpc_asyncio.py index dac7badcdbcd..46ed6f741c1f 100644 --- a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -251,6 +252,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -724,81 +728,115 @@ def revoke_grant( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.check_onboarding_status: gapic_v1.method_async.wrap_method( + self.check_onboarding_status: self._wrap_method( self.check_onboarding_status, default_timeout=None, client_info=client_info, ), - self.list_entitlements: gapic_v1.method_async.wrap_method( + self.list_entitlements: self._wrap_method( self.list_entitlements, default_timeout=None, client_info=client_info, ), - self.search_entitlements: gapic_v1.method_async.wrap_method( + self.search_entitlements: self._wrap_method( self.search_entitlements, default_timeout=None, client_info=client_info, ), - self.get_entitlement: gapic_v1.method_async.wrap_method( + self.get_entitlement: self._wrap_method( self.get_entitlement, default_timeout=None, client_info=client_info, ), - self.create_entitlement: gapic_v1.method_async.wrap_method( + self.create_entitlement: self._wrap_method( self.create_entitlement, default_timeout=None, client_info=client_info, ), - self.delete_entitlement: gapic_v1.method_async.wrap_method( + self.delete_entitlement: self._wrap_method( self.delete_entitlement, default_timeout=None, client_info=client_info, ), - self.update_entitlement: gapic_v1.method_async.wrap_method( + self.update_entitlement: self._wrap_method( self.update_entitlement, default_timeout=None, client_info=client_info, ), - self.list_grants: gapic_v1.method_async.wrap_method( + self.list_grants: self._wrap_method( self.list_grants, default_timeout=None, client_info=client_info, ), - self.search_grants: gapic_v1.method_async.wrap_method( + self.search_grants: self._wrap_method( self.search_grants, default_timeout=None, client_info=client_info, ), - self.get_grant: gapic_v1.method_async.wrap_method( + self.get_grant: self._wrap_method( self.get_grant, default_timeout=None, client_info=client_info, ), - self.create_grant: gapic_v1.method_async.wrap_method( + self.create_grant: self._wrap_method( self.create_grant, default_timeout=None, client_info=client_info, ), - self.approve_grant: gapic_v1.method_async.wrap_method( + self.approve_grant: self._wrap_method( self.approve_grant, default_timeout=None, client_info=client_info, ), - self.deny_grant: gapic_v1.method_async.wrap_method( + self.deny_grant: self._wrap_method( self.deny_grant, default_timeout=None, client_info=client_info, ), - self.revoke_grant: gapic_v1.method_async.wrap_method( + self.revoke_grant: self._wrap_method( self.revoke_grant, default_timeout=None, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest.py index 71a3702ad479..4bf98f62712d 100644 --- a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest.py +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.privilegedaccessmanager_v1.types import privilegedaccessmanager + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePrivilegedAccessManagerRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.privilegedaccessmanager_v1.types import privilegedaccessmanager - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PrivilegedAccessManagerTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -647,8 +637,8 @@ class PrivilegedAccessManagerRestStub: _interceptor: PrivilegedAccessManagerRestInterceptor -class PrivilegedAccessManagerRestTransport(PrivilegedAccessManagerTransport): - """REST backend transport for PrivilegedAccessManager. +class PrivilegedAccessManagerRestTransport(_BasePrivilegedAccessManagerRestTransport): + """REST backend synchronous transport for PrivilegedAccessManager. This API allows customers to manage temporary, request based privileged access to their resources. @@ -679,7 +669,6 @@ class PrivilegedAccessManagerRestTransport(PrivilegedAccessManagerTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -733,21 +722,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -829,19 +809,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ApproveGrant(PrivilegedAccessManagerRestStub): + class _ApproveGrant( + _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("ApproveGrant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.ApproveGrant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -872,55 +868,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:approve", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:approve", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:approve", - "body": "*", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant._get_http_options() + ) request, metadata = self._interceptor.pre_approve_grant(request, metadata) - pb_request = privilegedaccessmanager.ApproveGrantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PrivilegedAccessManagerRestTransport._ApproveGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -936,19 +909,34 @@ def __call__( resp = self._interceptor.post_approve_grant(resp) return resp - class _CheckOnboardingStatus(PrivilegedAccessManagerRestStub): + class _CheckOnboardingStatus( + _BasePrivilegedAccessManagerRestTransport._BaseCheckOnboardingStatus, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("CheckOnboardingStatus") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.CheckOnboardingStatus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -974,50 +962,29 @@ def __call__( Response message for ``CheckOnboardingStatus`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}:checkOnboardingStatus", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*}:checkOnboardingStatus", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*}:checkOnboardingStatus", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseCheckOnboardingStatus._get_http_options() + ) request, metadata = self._interceptor.pre_check_onboarding_status( request, metadata ) - pb_request = privilegedaccessmanager.CheckOnboardingStatusRequest.pb( - request + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseCheckOnboardingStatus._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseCheckOnboardingStatus._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivilegedAccessManagerRestTransport._CheckOnboardingStatus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1033,21 +1000,35 @@ def __call__( resp = self._interceptor.post_check_onboarding_status(resp) return resp - class _CreateEntitlement(PrivilegedAccessManagerRestStub): + class _CreateEntitlement( + _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("CreateEntitlement") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "entitlementId": "", - } - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.CreateEntitlement") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1076,57 +1057,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/entitlements", - "body": "entitlement", - }, - { - "method": "post", - "uri": "/v1/{parent=organizations/*/locations/*}/entitlements", - "body": "entitlement", - }, - { - "method": "post", - "uri": "/v1/{parent=folders/*/locations/*}/entitlements", - "body": "entitlement", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement._get_http_options() + ) request, metadata = self._interceptor.pre_create_entitlement( request, metadata ) - pb_request = privilegedaccessmanager.CreateEntitlementRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + PrivilegedAccessManagerRestTransport._CreateEntitlement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1140,19 +1100,35 @@ def __call__( resp = self._interceptor.post_create_entitlement(resp) return resp - class _CreateGrant(PrivilegedAccessManagerRestStub): + class _CreateGrant( + _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("CreateGrant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.CreateGrant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1183,55 +1159,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants", - "body": "grant", - }, - { - "method": "post", - "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants", - "body": "grant", - }, - { - "method": "post", - "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants", - "body": "grant", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant._get_http_options() + ) request, metadata = self._interceptor.pre_create_grant(request, metadata) - pb_request = privilegedaccessmanager.CreateGrantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PrivilegedAccessManagerRestTransport._CreateGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1247,19 +1200,34 @@ def __call__( resp = self._interceptor.post_create_grant(resp) return resp - class _DeleteEntitlement(PrivilegedAccessManagerRestStub): + class _DeleteEntitlement( + _BasePrivilegedAccessManagerRestTransport._BaseDeleteEntitlement, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("DeleteEntitlement") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.DeleteEntitlement") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1288,48 +1256,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*}", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseDeleteEntitlement._get_http_options() + ) request, metadata = self._interceptor.pre_delete_entitlement( request, metadata ) - pb_request = privilegedaccessmanager.DeleteEntitlementRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseDeleteEntitlement._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseDeleteEntitlement._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + PrivilegedAccessManagerRestTransport._DeleteEntitlement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1343,19 +1294,35 @@ def __call__( resp = self._interceptor.post_delete_entitlement(resp) return resp - class _DenyGrant(PrivilegedAccessManagerRestStub): + class _DenyGrant( + _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("DenyGrant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.DenyGrant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1386,55 +1353,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:deny", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:deny", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:deny", - "body": "*", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant._get_http_options() + ) request, metadata = self._interceptor.pre_deny_grant(request, metadata) - pb_request = privilegedaccessmanager.DenyGrantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PrivilegedAccessManagerRestTransport._DenyGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1450,19 +1394,34 @@ def __call__( resp = self._interceptor.post_deny_grant(resp) return resp - class _GetEntitlement(PrivilegedAccessManagerRestStub): + class _GetEntitlement( + _BasePrivilegedAccessManagerRestTransport._BaseGetEntitlement, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("GetEntitlement") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.GetEntitlement") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1493,46 +1452,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*}", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseGetEntitlement._get_http_options() + ) request, metadata = self._interceptor.pre_get_entitlement(request, metadata) - pb_request = privilegedaccessmanager.GetEntitlementRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseGetEntitlement._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseGetEntitlement._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + PrivilegedAccessManagerRestTransport._GetEntitlement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1548,19 +1490,34 @@ def __call__( resp = self._interceptor.post_get_entitlement(resp) return resp - class _GetGrant(PrivilegedAccessManagerRestStub): + class _GetGrant( + _BasePrivilegedAccessManagerRestTransport._BaseGetGrant, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("GetGrant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.GetGrant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1591,46 +1548,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseGetGrant._get_http_options() + ) request, metadata = self._interceptor.pre_get_grant(request, metadata) - pb_request = privilegedaccessmanager.GetGrantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseGetGrant._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseGetGrant._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivilegedAccessManagerRestTransport._GetGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1646,19 +1584,34 @@ def __call__( resp = self._interceptor.post_get_grant(resp) return resp - class _ListEntitlements(PrivilegedAccessManagerRestStub): + class _ListEntitlements( + _BasePrivilegedAccessManagerRestTransport._BaseListEntitlements, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("ListEntitlements") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.ListEntitlements") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1687,48 +1640,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/entitlements", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*}/entitlements", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*}/entitlements", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseListEntitlements._get_http_options() + ) request, metadata = self._interceptor.pre_list_entitlements( request, metadata ) - pb_request = privilegedaccessmanager.ListEntitlementsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseListEntitlements._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseListEntitlements._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + PrivilegedAccessManagerRestTransport._ListEntitlements._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1744,19 +1680,34 @@ def __call__( resp = self._interceptor.post_list_entitlements(resp) return resp - class _ListGrants(PrivilegedAccessManagerRestStub): + class _ListGrants( + _BasePrivilegedAccessManagerRestTransport._BaseListGrants, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("ListGrants") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.ListGrants") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1785,46 +1736,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseListGrants._get_http_options() + ) request, metadata = self._interceptor.pre_list_grants(request, metadata) - pb_request = privilegedaccessmanager.ListGrantsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseListGrants._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseListGrants._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivilegedAccessManagerRestTransport._ListGrants._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1840,19 +1772,35 @@ def __call__( resp = self._interceptor.post_list_grants(resp) return resp - class _RevokeGrant(PrivilegedAccessManagerRestStub): + class _RevokeGrant( + _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("RevokeGrant") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.RevokeGrant") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1881,55 +1829,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:revoke", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:revoke", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:revoke", - "body": "*", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant._get_http_options() + ) request, metadata = self._interceptor.pre_revoke_grant(request, metadata) - pb_request = privilegedaccessmanager.RevokeGrantRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PrivilegedAccessManagerRestTransport._RevokeGrant._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1943,21 +1868,34 @@ def __call__( resp = self._interceptor.post_revoke_grant(resp) return resp - class _SearchEntitlements(PrivilegedAccessManagerRestStub): + class _SearchEntitlements( + _BasePrivilegedAccessManagerRestTransport._BaseSearchEntitlements, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("SearchEntitlements") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "callerAccessType": {}, - } - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.SearchEntitlements") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1983,48 +1921,31 @@ def __call__( Response message for ``SearchEntitlements`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/entitlements:search", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*}/entitlements:search", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*}/entitlements:search", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseSearchEntitlements._get_http_options() + ) request, metadata = self._interceptor.pre_search_entitlements( request, metadata ) - pb_request = privilegedaccessmanager.SearchEntitlementsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseSearchEntitlements._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseSearchEntitlements._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + PrivilegedAccessManagerRestTransport._SearchEntitlements._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2040,21 +1961,34 @@ def __call__( resp = self._interceptor.post_search_entitlements(resp) return resp - class _SearchGrants(PrivilegedAccessManagerRestStub): + class _SearchGrants( + _BasePrivilegedAccessManagerRestTransport._BaseSearchGrants, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("SearchGrants") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "callerRelationship": {}, - } - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.SearchGrants") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -2080,46 +2014,27 @@ def __call__( Response message for ``SearchGrants`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants:search", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants:search", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants:search", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseSearchGrants._get_http_options() + ) request, metadata = self._interceptor.pre_search_grants(request, metadata) - pb_request = privilegedaccessmanager.SearchGrantsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseSearchGrants._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseSearchGrants._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PrivilegedAccessManagerRestTransport._SearchGrants._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2135,21 +2050,35 @@ def __call__( resp = self._interceptor.post_search_grants(resp) return resp - class _UpdateEntitlement(PrivilegedAccessManagerRestStub): + class _UpdateEntitlement( + _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement, + PrivilegedAccessManagerRestStub, + ): def __hash__(self): - return hash("UpdateEntitlement") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("PrivilegedAccessManagerRestTransport.UpdateEntitlement") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -2178,57 +2107,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{entitlement.name=projects/*/locations/*/entitlements/*}", - "body": "entitlement", - }, - { - "method": "patch", - "uri": "/v1/{entitlement.name=organizations/*/locations/*/entitlements/*}", - "body": "entitlement", - }, - { - "method": "patch", - "uri": "/v1/{entitlement.name=folders/*/locations/*/entitlements/*}", - "body": "entitlement", - }, - ] + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement._get_http_options() + ) request, metadata = self._interceptor.pre_update_entitlement( request, metadata ) - pb_request = privilegedaccessmanager.UpdateEntitlementRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + PrivilegedAccessManagerRestTransport._UpdateEntitlement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2392,7 +2300,35 @@ def update_entitlement( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(PrivilegedAccessManagerRestStub): + class _GetLocation( + _BasePrivilegedAccessManagerRestTransport._BaseGetLocation, + PrivilegedAccessManagerRestStub, + ): + def __hash__(self): + return hash("PrivilegedAccessManagerRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -2416,40 +2352,27 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*}", - }, - ] - + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) # 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), + response = PrivilegedAccessManagerRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2457,8 +2380,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -2466,7 +2390,35 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(PrivilegedAccessManagerRestStub): + class _ListLocations( + _BasePrivilegedAccessManagerRestTransport._BaseListLocations, + PrivilegedAccessManagerRestStub, + ): + def __hash__(self): + return hash("PrivilegedAccessManagerRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -2490,40 +2442,29 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*}/locations", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*}/locations", - }, - ] - + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + PrivilegedAccessManagerRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2531,8 +2472,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -2540,7 +2482,35 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(PrivilegedAccessManagerRestStub): + class _DeleteOperation( + _BasePrivilegedAccessManagerRestTransport._BaseDeleteOperation, + PrivilegedAccessManagerRestStub, + ): + def __hash__(self): + return hash("PrivilegedAccessManagerRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -2561,42 +2531,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=organizations/*/locations/*/operations/*}", - }, - { - "method": "delete", - "uri": "/v1/{name=folders/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + PrivilegedAccessManagerRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2610,7 +2569,35 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(PrivilegedAccessManagerRestStub): + class _GetOperation( + _BasePrivilegedAccessManagerRestTransport._BaseGetOperation, + PrivilegedAccessManagerRestStub, + ): + def __hash__(self): + return hash("PrivilegedAccessManagerRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -2634,40 +2621,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = PrivilegedAccessManagerRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2675,8 +2649,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -2684,7 +2659,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(PrivilegedAccessManagerRestStub): + class _ListOperations( + _BasePrivilegedAccessManagerRestTransport._BaseListOperations, + PrivilegedAccessManagerRestStub, + ): + def __hash__(self): + return hash("PrivilegedAccessManagerRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -2708,40 +2711,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*}/operations", - }, - ] - + http_options = ( + _BasePrivilegedAccessManagerRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePrivilegedAccessManagerRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePrivilegedAccessManagerRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + PrivilegedAccessManagerRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2749,8 +2741,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest_base.py b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest_base.py new file mode 100644 index 000000000000..36891b8825aa --- /dev/null +++ b/packages/google-cloud-privilegedaccessmanager/google/cloud/privilegedaccessmanager_v1/services/privileged_access_manager/transports/rest_base.py @@ -0,0 +1,1110 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.privilegedaccessmanager_v1.types import privilegedaccessmanager + +from .base import DEFAULT_CLIENT_INFO, PrivilegedAccessManagerTransport + + +class _BasePrivilegedAccessManagerRestTransport(PrivilegedAccessManagerTransport): + """Base REST backend transport for PrivilegedAccessManager. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "privilegedaccessmanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'privilegedaccessmanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseApproveGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:approve", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:approve", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:approve", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.ApproveGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseApproveGrant._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCheckOnboardingStatus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}:checkOnboardingStatus", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}:checkOnboardingStatus", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*}:checkOnboardingStatus", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.CheckOnboardingStatusRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseCheckOnboardingStatus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEntitlement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "entitlementId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/entitlements", + "body": "entitlement", + }, + { + "method": "post", + "uri": "/v1/{parent=organizations/*/locations/*}/entitlements", + "body": "entitlement", + }, + { + "method": "post", + "uri": "/v1/{parent=folders/*/locations/*}/entitlements", + "body": "entitlement", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.CreateEntitlementRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseCreateEntitlement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants", + "body": "grant", + }, + { + "method": "post", + "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants", + "body": "grant", + }, + { + "method": "post", + "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants", + "body": "grant", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.CreateGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseCreateGrant._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEntitlement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.DeleteEntitlementRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseDeleteEntitlement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDenyGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:deny", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:deny", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:deny", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.DenyGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseDenyGrant._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEntitlement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.GetEntitlementRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseGetEntitlement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.GetGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseGetGrant._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEntitlements: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/entitlements", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/entitlements", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*}/entitlements", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.ListEntitlementsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseListEntitlements._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGrants: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.ListGrantsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseListGrants._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRevokeGrant: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/entitlements/*/grants/*}:revoke", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/entitlements/*/grants/*}:revoke", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/entitlements/*/grants/*}:revoke", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.RevokeGrantRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseRevokeGrant._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchEntitlements: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "callerAccessType": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/entitlements:search", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/entitlements:search", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*}/entitlements:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.SearchEntitlementsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseSearchEntitlements._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchGrants: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "callerRelationship": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/entitlements/*}/grants:search", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/entitlements/*}/grants:search", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*/entitlements/*}/grants:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.SearchGrantsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseSearchGrants._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEntitlement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{entitlement.name=projects/*/locations/*/entitlements/*}", + "body": "entitlement", + }, + { + "method": "patch", + "uri": "/v1/{entitlement.name=organizations/*/locations/*/entitlements/*}", + "body": "entitlement", + }, + { + "method": "patch", + "uri": "/v1/{entitlement.name=folders/*/locations/*/entitlements/*}", + "body": "entitlement", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = privilegedaccessmanager.UpdateEntitlementRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePrivilegedAccessManagerRestTransport._BaseUpdateEntitlement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=folders/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePrivilegedAccessManagerRestTransport",) diff --git a/packages/google-cloud-privilegedaccessmanager/setup.py b/packages/google-cloud-privilegedaccessmanager/setup.py index 994ff77eb5ef..38808f37c98e 100644 --- a/packages/google-cloud-privilegedaccessmanager/setup.py +++ b/packages/google-cloud-privilegedaccessmanager/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-privilegedaccessmanager" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-privilegedaccessmanager/tests/unit/gapic/privilegedaccessmanager_v1/test_privileged_access_manager.py b/packages/google-cloud-privilegedaccessmanager/tests/unit/gapic/privilegedaccessmanager_v1/test_privileged_access_manager.py index 8f3bd6e95563..f77508750004 100644 --- a/packages/google-cloud-privilegedaccessmanager/tests/unit/gapic/privilegedaccessmanager_v1/test_privileged_access_manager.py +++ b/packages/google-cloud-privilegedaccessmanager/tests/unit/gapic/privilegedaccessmanager_v1/test_privileged_access_manager.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,16 +65,8 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import duration_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 -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.privilegedaccessmanager_v1.services.privileged_access_manager import ( PrivilegedAccessManagerAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.privilegedaccessmanager_v1.types import privilegedaccessmanager +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1243,27 +1266,6 @@ def test_check_onboarding_status(request_type, transport: str = "grpc"): assert response.service_account == "service_account_value" -def test_check_onboarding_status_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_onboarding_status), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.check_onboarding_status() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CheckOnboardingStatusRequest() - - def test_check_onboarding_status_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1334,31 +1336,6 @@ def test_check_onboarding_status_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_check_onboarding_status_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_onboarding_status), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.CheckOnboardingStatusResponse( - service_account="service_account_value", - ) - ) - response = await client.check_onboarding_status() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CheckOnboardingStatusRequest() - - @pytest.mark.asyncio async def test_check_onboarding_status_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1367,7 +1344,7 @@ async def test_check_onboarding_status_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1407,7 +1384,7 @@ async def test_check_onboarding_status_async( request_type=privilegedaccessmanager.CheckOnboardingStatusRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1477,7 +1454,7 @@ def test_check_onboarding_status_field_headers(): @pytest.mark.asyncio async def test_check_onboarding_status_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1548,27 +1525,6 @@ def test_list_entitlements(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_entitlements_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entitlements), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_entitlements() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ListEntitlementsRequest() - - def test_list_entitlements_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1642,32 +1598,6 @@ def test_list_entitlements_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_entitlements_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_entitlements), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.ListEntitlementsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_entitlements() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ListEntitlementsRequest() - - @pytest.mark.asyncio async def test_list_entitlements_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1676,7 +1606,7 @@ async def test_list_entitlements_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1716,7 +1646,7 @@ async def test_list_entitlements_async( request_type=privilegedaccessmanager.ListEntitlementsRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1788,7 +1718,7 @@ def test_list_entitlements_field_headers(): @pytest.mark.asyncio async def test_list_entitlements_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1862,7 +1792,7 @@ def test_list_entitlements_flattened_error(): @pytest.mark.asyncio async def test_list_entitlements_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1893,7 +1823,7 @@ async def test_list_entitlements_flattened_async(): @pytest.mark.asyncio async def test_list_entitlements_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2007,7 +1937,7 @@ def test_list_entitlements_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_entitlements_async_pager(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2061,7 +1991,7 @@ async def test_list_entitlements_async_pager(): @pytest.mark.asyncio async def test_list_entitlements_async_pages(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2147,27 +2077,6 @@ def test_search_entitlements(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_entitlements_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_entitlements), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_entitlements() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.SearchEntitlementsRequest() - - def test_search_entitlements_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2241,31 +2150,6 @@ def test_search_entitlements_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_entitlements_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_entitlements), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.SearchEntitlementsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_entitlements() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.SearchEntitlementsRequest() - - @pytest.mark.asyncio async def test_search_entitlements_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2274,7 +2158,7 @@ async def test_search_entitlements_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2314,7 +2198,7 @@ async def test_search_entitlements_async( request_type=privilegedaccessmanager.SearchEntitlementsRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2384,7 +2268,7 @@ def test_search_entitlements_field_headers(): @pytest.mark.asyncio async def test_search_entitlements_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2517,7 +2401,7 @@ def test_search_entitlements_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_entitlements_async_pager(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2571,7 +2455,7 @@ async def test_search_entitlements_async_pager(): @pytest.mark.asyncio async def test_search_entitlements_async_pages(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2659,25 +2543,6 @@ def test_get_entitlement(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_entitlement_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_entitlement), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.GetEntitlementRequest() - - def test_get_entitlement_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2741,31 +2606,6 @@ def test_get_entitlement_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_entitlement_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_entitlement), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.Entitlement( - name="name_value", - state=privilegedaccessmanager.Entitlement.State.CREATING, - etag="etag_value", - ) - ) - response = await client.get_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.GetEntitlementRequest() - - @pytest.mark.asyncio async def test_get_entitlement_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2774,7 +2614,7 @@ async def test_get_entitlement_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2814,7 +2654,7 @@ async def test_get_entitlement_async( request_type=privilegedaccessmanager.GetEntitlementRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2884,7 +2724,7 @@ def test_get_entitlement_field_headers(): @pytest.mark.asyncio async def test_get_entitlement_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2954,7 +2794,7 @@ def test_get_entitlement_flattened_error(): @pytest.mark.asyncio async def test_get_entitlement_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2983,7 +2823,7 @@ async def test_get_entitlement_flattened_async(): @pytest.mark.asyncio async def test_get_entitlement_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3030,27 +2870,6 @@ def test_create_entitlement(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_entitlement_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entitlement), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CreateEntitlementRequest() - - def test_create_entitlement_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3129,29 +2948,6 @@ def test_create_entitlement_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_entitlement_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_entitlement), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CreateEntitlementRequest() - - @pytest.mark.asyncio async def test_create_entitlement_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3160,7 +2956,7 @@ async def test_create_entitlement_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3205,7 +3001,7 @@ async def test_create_entitlement_async( request_type=privilegedaccessmanager.CreateEntitlementRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3272,7 +3068,7 @@ def test_create_entitlement_field_headers(): @pytest.mark.asyncio async def test_create_entitlement_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3356,7 +3152,7 @@ def test_create_entitlement_flattened_error(): @pytest.mark.asyncio async def test_create_entitlement_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3395,7 +3191,7 @@ async def test_create_entitlement_flattened_async(): @pytest.mark.asyncio async def test_create_entitlement_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3444,27 +3240,6 @@ def test_delete_entitlement(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_entitlement_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entitlement), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.DeleteEntitlementRequest() - - def test_delete_entitlement_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3542,39 +3317,16 @@ def test_delete_entitlement_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_entitlement_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_entitlement), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.DeleteEntitlementRequest() - - -@pytest.mark.asyncio -async def test_delete_entitlement_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_delete_entitlement_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3617,7 +3369,7 @@ async def test_delete_entitlement_async( request_type=privilegedaccessmanager.DeleteEntitlementRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3684,7 +3436,7 @@ def test_delete_entitlement_field_headers(): @pytest.mark.asyncio async def test_delete_entitlement_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3758,7 +3510,7 @@ def test_delete_entitlement_flattened_error(): @pytest.mark.asyncio async def test_delete_entitlement_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3789,7 +3541,7 @@ async def test_delete_entitlement_flattened_async(): @pytest.mark.asyncio async def test_delete_entitlement_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3836,27 +3588,6 @@ def test_update_entitlement(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_entitlement_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entitlement), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.UpdateEntitlementRequest() - - def test_update_entitlement_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3927,29 +3658,6 @@ def test_update_entitlement_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_entitlement_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_entitlement), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_entitlement() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.UpdateEntitlementRequest() - - @pytest.mark.asyncio async def test_update_entitlement_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3958,7 +3666,7 @@ async def test_update_entitlement_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4003,7 +3711,7 @@ async def test_update_entitlement_async( request_type=privilegedaccessmanager.UpdateEntitlementRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4070,7 +3778,7 @@ def test_update_entitlement_field_headers(): @pytest.mark.asyncio async def test_update_entitlement_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4149,7 +3857,7 @@ def test_update_entitlement_flattened_error(): @pytest.mark.asyncio async def test_update_entitlement_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4184,7 +3892,7 @@ async def test_update_entitlement_flattened_async(): @pytest.mark.asyncio async def test_update_entitlement_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4235,25 +3943,6 @@ def test_list_grants(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_grants_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_grants), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_grants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ListGrantsRequest() - - def test_list_grants_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4323,30 +4012,6 @@ def test_list_grants_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_grants_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_grants), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.ListGrantsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_grants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ListGrantsRequest() - - @pytest.mark.asyncio async def test_list_grants_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4355,7 +4020,7 @@ async def test_list_grants_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4395,7 +4060,7 @@ async def test_list_grants_async( request_type=privilegedaccessmanager.ListGrantsRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4463,7 +4128,7 @@ def test_list_grants_field_headers(): @pytest.mark.asyncio async def test_list_grants_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4533,7 +4198,7 @@ def test_list_grants_flattened_error(): @pytest.mark.asyncio async def test_list_grants_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4562,7 +4227,7 @@ async def test_list_grants_flattened_async(): @pytest.mark.asyncio async def test_list_grants_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4672,7 +4337,7 @@ def test_list_grants_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_grants_async_pager(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4722,7 +4387,7 @@ async def test_list_grants_async_pager(): @pytest.mark.asyncio async def test_list_grants_async_pages(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4804,25 +4469,6 @@ def test_search_grants(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_grants_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_grants), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_grants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.SearchGrantsRequest() - - def test_search_grants_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4890,29 +4536,6 @@ def test_search_grants_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_grants_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_grants), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.SearchGrantsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_grants() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.SearchGrantsRequest() - - @pytest.mark.asyncio async def test_search_grants_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4921,7 +4544,7 @@ async def test_search_grants_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4961,7 +4584,7 @@ async def test_search_grants_async( request_type=privilegedaccessmanager.SearchGrantsRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5027,7 +4650,7 @@ def test_search_grants_field_headers(): @pytest.mark.asyncio async def test_search_grants_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5154,7 +4777,7 @@ def test_search_grants_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_grants_async_pager(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5204,7 +4827,7 @@ async def test_search_grants_async_pager(): @pytest.mark.asyncio async def test_search_grants_async_pages(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5294,25 +4917,6 @@ def test_get_grant(request_type, transport: str = "grpc"): assert response.externally_modified is True -def test_get_grant_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_grant), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.GetGrantRequest() - - def test_get_grant_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5376,40 +4980,13 @@ def test_get_grant_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_grant_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_grant), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - ) - response = await client.get_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.GetGrantRequest() - - @pytest.mark.asyncio async def test_get_grant_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5449,7 +5026,7 @@ async def test_get_grant_async( request_type=privilegedaccessmanager.GetGrantRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5523,7 +5100,7 @@ def test_get_grant_field_headers(): @pytest.mark.asyncio async def test_get_grant_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5593,7 +5170,7 @@ def test_get_grant_flattened_error(): @pytest.mark.asyncio async def test_get_grant_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5622,7 +5199,7 @@ async def test_get_grant_flattened_async(): @pytest.mark.asyncio async def test_get_grant_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5678,25 +5255,6 @@ def test_create_grant(request_type, transport: str = "grpc"): assert response.externally_modified is True -def test_create_grant_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_grant), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CreateGrantRequest() - - def test_create_grant_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5762,33 +5320,6 @@ def test_create_grant_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_grant_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_grant), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - ) - response = await client.create_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.CreateGrantRequest() - - @pytest.mark.asyncio async def test_create_grant_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5797,7 +5328,7 @@ async def test_create_grant_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5837,7 +5368,7 @@ async def test_create_grant_async( request_type=privilegedaccessmanager.CreateGrantRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5911,7 +5442,7 @@ def test_create_grant_field_headers(): @pytest.mark.asyncio async def test_create_grant_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5986,7 +5517,7 @@ def test_create_grant_flattened_error(): @pytest.mark.asyncio async def test_create_grant_flattened_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6019,7 +5550,7 @@ async def test_create_grant_flattened_async(): @pytest.mark.asyncio async def test_create_grant_flattened_error_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6076,25 +5607,6 @@ def test_approve_grant(request_type, transport: str = "grpc"): assert response.externally_modified is True -def test_approve_grant_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.approve_grant), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.approve_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ApproveGrantRequest() - - def test_approve_grant_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6161,43 +5673,16 @@ def test_approve_grant_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_approve_grant_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.approve_grant), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - ) - response = await client.approve_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.ApproveGrantRequest() - - -@pytest.mark.asyncio -async def test_approve_grant_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_approve_grant_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -6235,7 +5720,7 @@ async def test_approve_grant_async( request_type=privilegedaccessmanager.ApproveGrantRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6309,7 +5794,7 @@ def test_approve_grant_field_headers(): @pytest.mark.asyncio async def test_approve_grant_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6382,25 +5867,6 @@ def test_deny_grant(request_type, transport: str = "grpc"): assert response.externally_modified is True -def test_deny_grant_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.deny_grant), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.deny_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.DenyGrantRequest() - - def test_deny_grant_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6466,40 +5932,13 @@ def test_deny_grant_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_deny_grant_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.deny_grant), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - ) - response = await client.deny_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.DenyGrantRequest() - - @pytest.mark.asyncio async def test_deny_grant_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6539,7 +5978,7 @@ async def test_deny_grant_async( request_type=privilegedaccessmanager.DenyGrantRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6613,7 +6052,7 @@ def test_deny_grant_field_headers(): @pytest.mark.asyncio async def test_deny_grant_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6675,25 +6114,6 @@ def test_revoke_grant(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_revoke_grant_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.revoke_grant), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.revoke_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.RevokeGrantRequest() - - def test_revoke_grant_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6764,27 +6184,6 @@ def test_revoke_grant_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_revoke_grant_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.revoke_grant), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.revoke_grant() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == privilegedaccessmanager.RevokeGrantRequest() - - @pytest.mark.asyncio async def test_revoke_grant_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6793,7 +6192,7 @@ async def test_revoke_grant_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6838,7 +6237,7 @@ async def test_revoke_grant_async( request_type=privilegedaccessmanager.RevokeGrantRequest, ): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6901,7 +6300,7 @@ def test_revoke_grant_field_headers(): @pytest.mark.asyncio async def test_revoke_grant_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6930,48 +6329,6 @@ async def test_revoke_grant_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.CheckOnboardingStatusRequest, - dict, - ], -) -def test_check_onboarding_status_rest(request_type): - client = PrivilegedAccessManagerClient( - 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 = privilegedaccessmanager.CheckOnboardingStatusResponse( - service_account="service_account_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.CheckOnboardingStatusResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.check_onboarding_status(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.CheckOnboardingStatusResponse) - assert response.service_account == "service_account_value" - - def test_check_onboarding_status_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7098,200 +6455,67 @@ def test_check_onboarding_status_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_check_onboarding_status_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, - "post_check_onboarding_status", - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_check_onboarding_status" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.CheckOnboardingStatusRequest.pb( - privilegedaccessmanager.CheckOnboardingStatusRequest() +def test_list_entitlements_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = ( - privilegedaccessmanager.CheckOnboardingStatusResponse.to_json( - privilegedaccessmanager.CheckOnboardingStatusResponse() - ) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - request = privilegedaccessmanager.CheckOnboardingStatusRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.CheckOnboardingStatusResponse() + # Ensure method has been cached + assert client._transport.list_entitlements in client._transport._wrapped_methods - client.check_onboarding_status( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.list_entitlements + ] = mock_rpc - pre.assert_called_once() - post.assert_called_once() + request = {} + client.list_entitlements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_entitlements(request) -def test_check_onboarding_status_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.CheckOnboardingStatusRequest, + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_entitlements_rest_required_fields( + request_type=privilegedaccessmanager.ListEntitlementsRequest, ): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + transport_class = transports.PrivilegedAccessManagerRestTransport - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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, use_integers_for_enums=False) + ) - # 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.check_onboarding_status(request) + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_entitlements._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_check_onboarding_status_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # verify required fields with default values are now present - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.ListEntitlementsRequest, - dict, - ], -) -def test_list_entitlements_rest(request_type): - client = PrivilegedAccessManagerClient( - 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 = privilegedaccessmanager.ListEntitlementsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.ListEntitlementsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_entitlements(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntitlementsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_entitlements_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_entitlements in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_entitlements - ] = mock_rpc - - request = {} - client.list_entitlements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_entitlements(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_entitlements_rest_required_fields( - request_type=privilegedaccessmanager.ListEntitlementsRequest, -): - transport_class = transports.PrivilegedAccessManagerRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_entitlements._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" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() @@ -7373,90 +6597,6 @@ def test_list_entitlements_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_entitlements_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_list_entitlements" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_list_entitlements" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.ListEntitlementsRequest.pb( - privilegedaccessmanager.ListEntitlementsRequest() - ) - 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 = ( - privilegedaccessmanager.ListEntitlementsResponse.to_json( - privilegedaccessmanager.ListEntitlementsResponse() - ) - ) - - request = privilegedaccessmanager.ListEntitlementsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.ListEntitlementsResponse() - - client.list_entitlements( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_entitlements_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.ListEntitlementsRequest, -): - client = PrivilegedAccessManagerClient( - 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.list_entitlements(request) - - def test_list_entitlements_rest_flattened(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7578,48 +6718,6 @@ def test_list_entitlements_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.SearchEntitlementsRequest, - dict, - ], -) -def test_search_entitlements_rest(request_type): - client = PrivilegedAccessManagerClient( - 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 = privilegedaccessmanager.SearchEntitlementsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.SearchEntitlementsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_entitlements(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchEntitlementsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_entitlements_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7769,94 +6867,10 @@ def test_search_entitlements_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_entitlements_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( +def test_search_entitlements_rest_pager(transport: str = "rest"): + client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_search_entitlements" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_search_entitlements" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.SearchEntitlementsRequest.pb( - privilegedaccessmanager.SearchEntitlementsRequest() - ) - 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 = ( - privilegedaccessmanager.SearchEntitlementsResponse.to_json( - privilegedaccessmanager.SearchEntitlementsResponse() - ) - ) - - request = privilegedaccessmanager.SearchEntitlementsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.SearchEntitlementsResponse() - - client.search_entitlements( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_entitlements_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.SearchEntitlementsRequest, -): - client = PrivilegedAccessManagerClient( - 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.search_entitlements(request) - - -def test_search_entitlements_rest_pager(transport: str = "rest"): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport, ) # Mock the http request call within the method and fake a response. @@ -7917,50 +6931,6 @@ def test_search_entitlements_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.GetEntitlementRequest, - dict, - ], -) -def test_get_entitlement_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.Entitlement( - name="name_value", - state=privilegedaccessmanager.Entitlement.State.CREATING, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.Entitlement.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_entitlement(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.Entitlement) - assert response.name == "name_value" - assert response.state == privilegedaccessmanager.Entitlement.State.CREATING - assert response.etag == "etag_value" - - def test_get_entitlement_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8080,87 +7050,6 @@ def test_get_entitlement_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_entitlement_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_get_entitlement" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_get_entitlement" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.GetEntitlementRequest.pb( - privilegedaccessmanager.GetEntitlementRequest() - ) - 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 = privilegedaccessmanager.Entitlement.to_json( - privilegedaccessmanager.Entitlement() - ) - - request = privilegedaccessmanager.GetEntitlementRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.Entitlement() - - client.get_entitlement( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_entitlement_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.GetEntitlementRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/entitlements/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.get_entitlement(request) - - def test_get_entitlement_rest_flattened(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8220,219 +7109,62 @@ def test_get_entitlement_rest_flattened_error(transport: str = "rest"): ) -def test_get_entitlement_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_entitlement_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.CreateEntitlementRequest, - dict, - ], -) -def test_create_entitlement_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["entitlement"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "eligible_users": [{"principals": ["principals_value1", "principals_value2"]}], - "approval_workflow": { - "manual_approvals": { - "require_approver_justification": True, - "steps": [ - { - "approvers": {}, - "approvals_needed": 1692, - "approver_email_recipients": [ - "approver_email_recipients_value1", - "approver_email_recipients_value2", - ], - } - ], - } - }, - "privileged_access": { - "gcp_iam_access": { - "resource_type": "resource_type_value", - "resource": "resource_value", - "role_bindings": [ - { - "role": "role_value", - "condition_expression": "condition_expression_value", - } - ], - } - }, - "max_request_duration": {"seconds": 751, "nanos": 543}, - "state": 1, - "requester_justification_config": {"not_mandatory": {}, "unstructured": {}}, - "additional_notification_targets": { - "admin_email_recipients": [ - "admin_email_recipients_value1", - "admin_email_recipients_value2", - ], - "requester_email_recipients": [ - "requester_email_recipients_value1", - "requester_email_recipients_value2", - ], - }, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = privilegedaccessmanager.CreateEntitlementRequest.meta.fields[ - "entitlement" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["entitlement"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["entitlement"][field])): - del request_init["entitlement"][field][i][subfield] - else: - del request_init["entitlement"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_entitlement(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_entitlement_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_entitlement in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_entitlement - ] = mock_rpc - - request = {} - client.create_entitlement(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_entitlement(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_entitlement_rest_required_fields( - request_type=privilegedaccessmanager.CreateEntitlementRequest, -): - transport_class = transports.PrivilegedAccessManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["entitlement_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + # Ensure method has been cached + assert ( + client._transport.create_entitlement in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_entitlement + ] = mock_rpc + + request = {} + client.create_entitlement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_entitlement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_entitlement_rest_required_fields( + request_type=privilegedaccessmanager.CreateEntitlementRequest, +): + transport_class = transports.PrivilegedAccessManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["entitlement_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped @@ -8536,90 +7268,6 @@ def test_create_entitlement_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_entitlement_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "post_create_entitlement" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_create_entitlement" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.CreateEntitlementRequest.pb( - privilegedaccessmanager.CreateEntitlementRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = privilegedaccessmanager.CreateEntitlementRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_entitlement( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_entitlement_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.CreateEntitlementRequest, -): - client = PrivilegedAccessManagerClient( - 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.create_entitlement(request) - - def test_create_entitlement_rest_flattened(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8679,47 +7327,6 @@ def test_create_entitlement_rest_flattened_error(transport: str = "rest"): ) -def test_create_entitlement_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.DeleteEntitlementRequest, - dict, - ], -) -def test_delete_entitlement_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_entitlement(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_entitlement_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8859,90 +7466,6 @@ def test_delete_entitlement_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_entitlement_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "post_delete_entitlement" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_delete_entitlement" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.DeleteEntitlementRequest.pb( - privilegedaccessmanager.DeleteEntitlementRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = privilegedaccessmanager.DeleteEntitlementRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_entitlement( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_entitlement_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.DeleteEntitlementRequest, -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/entitlements/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.delete_entitlement(request) - - def test_delete_entitlement_rest_flattened(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9000,209 +7523,48 @@ def test_delete_entitlement_rest_flattened_error(transport: str = "rest"): ) -def test_delete_entitlement_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_entitlement_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.UpdateEntitlementRequest, - dict, - ], -) -def test_update_entitlement_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert ( + client._transport.update_entitlement in client._transport._wrapped_methods + ) - # send a request that will satisfy transcoding - request_init = { - "entitlement": { - "name": "projects/sample1/locations/sample2/entitlements/sample3" - } - } - request_init["entitlement"] = { - "name": "projects/sample1/locations/sample2/entitlements/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "eligible_users": [{"principals": ["principals_value1", "principals_value2"]}], - "approval_workflow": { - "manual_approvals": { - "require_approver_justification": True, - "steps": [ - { - "approvers": {}, - "approvals_needed": 1692, - "approver_email_recipients": [ - "approver_email_recipients_value1", - "approver_email_recipients_value2", - ], - } - ], - } - }, - "privileged_access": { - "gcp_iam_access": { - "resource_type": "resource_type_value", - "resource": "resource_value", - "role_bindings": [ - { - "role": "role_value", - "condition_expression": "condition_expression_value", - } - ], - } - }, - "max_request_duration": {"seconds": 751, "nanos": 543}, - "state": 1, - "requester_justification_config": {"not_mandatory": {}, "unstructured": {}}, - "additional_notification_targets": { - "admin_email_recipients": [ - "admin_email_recipients_value1", - "admin_email_recipients_value2", - ], - "requester_email_recipients": [ - "requester_email_recipients_value1", - "requester_email_recipients_value2", - ], - }, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_entitlement + ] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = privilegedaccessmanager.UpdateEntitlementRequest.meta.fields[ - "entitlement" - ] + request = {} + client.update_entitlement(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.update_entitlement(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["entitlement"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["entitlement"][field])): - del request_init["entitlement"][field][i][subfield] - else: - del request_init["entitlement"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_entitlement(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_entitlement_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_entitlement in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_entitlement - ] = mock_rpc - - request = {} - client.update_entitlement(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_entitlement(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 def test_update_entitlement_rest_required_fields( @@ -9291,94 +7653,6 @@ def test_update_entitlement_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_entitlement_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "post_update_entitlement" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_update_entitlement" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.UpdateEntitlementRequest.pb( - privilegedaccessmanager.UpdateEntitlementRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = privilegedaccessmanager.UpdateEntitlementRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_entitlement( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_entitlement_rest_bad_request( - transport: str = "rest", - request_type=privilegedaccessmanager.UpdateEntitlementRequest, -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "entitlement": { - "name": "projects/sample1/locations/sample2/entitlements/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.update_entitlement(request) - - def test_update_entitlement_rest_flattened(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9440,54 +7714,6 @@ def test_update_entitlement_rest_flattened_error(transport: str = "rest"): ) -def test_update_entitlement_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.ListGrantsRequest, - dict, - ], -) -def test_list_grants_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.ListGrantsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.ListGrantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_grants(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGrantsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_grants_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9626,97 +7852,16 @@ def test_list_grants_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_grants_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( +def test_list_grants_rest_flattened(): + client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), + transport="rest", ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_list_grants" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_list_grants" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.ListGrantsRequest.pb( - privilegedaccessmanager.ListGrantsRequest() - ) - 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 = privilegedaccessmanager.ListGrantsResponse.to_json( - privilegedaccessmanager.ListGrantsResponse() - ) - - request = privilegedaccessmanager.ListGrantsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.ListGrantsResponse() - - client.list_grants( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_grants_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.ListGrantsRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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.list_grants(request) - - -def test_list_grants_rest_flattened(): - client = PrivilegedAccessManagerClient( - 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 = privilegedaccessmanager.ListGrantsResponse() + # 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 = privilegedaccessmanager.ListGrantsResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -9831,46 +7976,6 @@ def test_list_grants_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.SearchGrantsRequest, - dict, - ], -) -def test_search_grants_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.SearchGrantsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.SearchGrantsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_grants(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchGrantsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_grants_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10014,89 +8119,6 @@ def test_search_grants_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_grants_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_search_grants" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_search_grants" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.SearchGrantsRequest.pb( - privilegedaccessmanager.SearchGrantsRequest() - ) - 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 = ( - privilegedaccessmanager.SearchGrantsResponse.to_json( - privilegedaccessmanager.SearchGrantsResponse() - ) - ) - - request = privilegedaccessmanager.SearchGrantsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.SearchGrantsResponse() - - client.search_grants( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_grants_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.SearchGrantsRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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.search_grants(request) - - def test_search_grants_rest_pager(transport: str = "rest"): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10162,56 +8184,6 @@ def test_search_grants_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.GetGrantRequest, - dict, - ], -) -def test_get_grant_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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 = privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.Grant.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_grant(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.Grant) - assert response.name == "name_value" - assert response.requester == "requester_value" - assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED - assert response.additional_email_recipients == ["additional_email_recipients_value"] - assert response.externally_modified is True - - def test_get_grant_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10331,99 +8303,16 @@ def test_get_grant_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_grant_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( +def test_get_grant_rest_flattened(): + client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), + transport="rest", ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_get_grant" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_get_grant" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.GetGrantRequest.pb( - privilegedaccessmanager.GetGrantRequest() - ) - 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 = privilegedaccessmanager.Grant.to_json( - privilegedaccessmanager.Grant() - ) - - request = privilegedaccessmanager.GetGrantRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.Grant() - - client.get_grant( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_grant_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.GetGrantRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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_grant(request) - - -def test_get_grant_rest_flattened(): - client = PrivilegedAccessManagerClient( - 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 = privilegedaccessmanager.Grant() + # 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 = privilegedaccessmanager.Grant() # get arguments that satisfy an http rule for this method sample_request = { @@ -10473,184 +8362,6 @@ def test_get_grant_rest_flattened_error(transport: str = "rest"): ) -def test_get_grant_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.CreateGrantRequest, - dict, - ], -) -def test_create_grant_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/sample3"} - request_init["grant"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "requester": "requester_value", - "requested_duration": {"seconds": 751, "nanos": 543}, - "justification": { - "unstructured_justification": "unstructured_justification_value" - }, - "state": 1, - "timeline": { - "events": [ - { - "requested": {"expire_time": {}}, - "approved": {"reason": "reason_value", "actor": "actor_value"}, - "denied": {"reason": "reason_value", "actor": "actor_value"}, - "revoked": {"reason": "reason_value", "actor": "actor_value"}, - "scheduled": {"scheduled_activation_time": {}}, - "activated": {}, - "activation_failed": { - "error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - } - }, - "expired": {}, - "ended": {}, - "externally_modified": {}, - "event_time": {}, - } - ] - }, - "privileged_access": { - "gcp_iam_access": { - "resource_type": "resource_type_value", - "resource": "resource_value", - "role_bindings": [ - { - "role": "role_value", - "condition_expression": "condition_expression_value", - } - ], - } - }, - "audit_trail": {"access_grant_time": {}, "access_remove_time": {}}, - "additional_email_recipients": [ - "additional_email_recipients_value1", - "additional_email_recipients_value2", - ], - "externally_modified": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = privilegedaccessmanager.CreateGrantRequest.meta.fields["grant"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["grant"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["grant"][field])): - del request_init["grant"][field][i][subfield] - else: - del request_init["grant"][field][subfield] - 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 = privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.Grant.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_grant(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.Grant) - assert response.name == "name_value" - assert response.requester == "requester_value" - assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED - assert response.additional_email_recipients == ["additional_email_recipients_value"] - assert response.externally_modified is True - - def test_create_grant_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10781,91 +8492,10 @@ def test_create_grant_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_grant_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( +def test_create_grant_rest_flattened(): + client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_create_grant" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_create_grant" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.CreateGrantRequest.pb( - privilegedaccessmanager.CreateGrantRequest() - ) - 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 = privilegedaccessmanager.Grant.to_json( - privilegedaccessmanager.Grant() - ) - - request = privilegedaccessmanager.CreateGrantRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.Grant() - - client.create_grant( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_grant_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.CreateGrantRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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.create_grant(request) - - -def test_create_grant_rest_flattened(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -10923,62 +8553,6 @@ def test_create_grant_rest_flattened_error(transport: str = "rest"): ) -def test_create_grant_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.ApproveGrantRequest, - dict, - ], -) -def test_approve_grant_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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 = privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.Grant.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.approve_grant(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.Grant) - assert response.name == "name_value" - assert response.requester == "requester_value" - assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED - assert response.additional_email_recipients == ["additional_email_recipients_value"] - assert response.externally_modified is True - - def test_approve_grant_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11099,145 +8673,6 @@ def test_approve_grant_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_approve_grant_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_approve_grant" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_approve_grant" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.ApproveGrantRequest.pb( - privilegedaccessmanager.ApproveGrantRequest() - ) - 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 = privilegedaccessmanager.Grant.to_json( - privilegedaccessmanager.Grant() - ) - - request = privilegedaccessmanager.ApproveGrantRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.Grant() - - client.approve_grant( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_approve_grant_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.ApproveGrantRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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.approve_grant(request) - - -def test_approve_grant_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.DenyGrantRequest, - dict, - ], -) -def test_deny_grant_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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 = privilegedaccessmanager.Grant( - name="name_value", - requester="requester_value", - state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, - additional_email_recipients=["additional_email_recipients_value"], - externally_modified=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = privilegedaccessmanager.Grant.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.deny_grant(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, privilegedaccessmanager.Grant) - assert response.name == "name_value" - assert response.requester == "requester_value" - assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED - assert response.additional_email_recipients == ["additional_email_recipients_value"] - assert response.externally_modified is True - - def test_deny_grant_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11358,132 +8793,6 @@ def test_deny_grant_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_deny_grant_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_deny_grant" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_deny_grant" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.DenyGrantRequest.pb( - privilegedaccessmanager.DenyGrantRequest() - ) - 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 = privilegedaccessmanager.Grant.to_json( - privilegedaccessmanager.Grant() - ) - - request = privilegedaccessmanager.DenyGrantRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = privilegedaccessmanager.Grant() - - client.deny_grant( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_deny_grant_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.DenyGrantRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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.deny_grant(request) - - -def test_deny_grant_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - privilegedaccessmanager.RevokeGrantRequest, - dict, - ], -) -def test_revoke_grant_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.revoke_grant(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_revoke_grant_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11605,97 +8914,6 @@ def test_revoke_grant_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_revoke_grant_rest_interceptors(null_interceptor): - transport = transports.PrivilegedAccessManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PrivilegedAccessManagerRestInterceptor(), - ) - client = PrivilegedAccessManagerClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "post_revoke_grant" - ) as post, mock.patch.object( - transports.PrivilegedAccessManagerRestInterceptor, "pre_revoke_grant" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = privilegedaccessmanager.RevokeGrantRequest.pb( - privilegedaccessmanager.RevokeGrantRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = privilegedaccessmanager.RevokeGrantRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.revoke_grant( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_revoke_grant_rest_bad_request( - transport: str = "rest", request_type=privilegedaccessmanager.RevokeGrantRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" - } - 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.revoke_grant(request) - - -def test_revoke_grant_rest_error(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PrivilegedAccessManagerGrpcTransport( @@ -11788,1047 +9006,4164 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PrivilegedAccessManagerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = PrivilegedAccessManagerClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_check_onboarding_status_empty_call_grpc(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert isinstance( - client.transport, - transports.PrivilegedAccessManagerGrpcTransport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_onboarding_status), "__call__" + ) as call: + call.return_value = privilegedaccessmanager.CheckOnboardingStatusResponse() + client.check_onboarding_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CheckOnboardingStatusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_entitlements_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_entitlements), "__call__" + ) as call: + call.return_value = privilegedaccessmanager.ListEntitlementsResponse() + client.list_entitlements(request=None) -def test_privileged_access_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PrivilegedAccessManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListEntitlementsRequest() + assert args[0] == request_msg -def test_privileged_access_manager_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.PrivilegedAccessManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "check_onboarding_status", - "list_entitlements", - "search_entitlements", - "get_entitlement", - "create_entitlement", - "delete_entitlement", - "update_entitlement", - "list_grants", - "search_grants", - "get_grant", - "create_grant", - "approve_grant", - "deny_grant", - "revoke_grant", - "get_location", - "list_locations", - "get_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_entitlements_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_entitlements), "__call__" + ) as call: + call.return_value = privilegedaccessmanager.SearchEntitlementsResponse() + client.search_entitlements(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchEntitlementsRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_privileged_access_manager_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.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PrivilegedAccessManagerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_entitlement_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_entitlement), "__call__") as call: + call.return_value = privilegedaccessmanager.Entitlement() + client.get_entitlement(request=None) -def test_privileged_access_manager_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PrivilegedAccessManagerTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetEntitlementRequest() + assert args[0] == request_msg -def test_privileged_access_manager_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PrivilegedAccessManagerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_entitlement_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivilegedAccessManagerGrpcTransport, - transports.PrivilegedAccessManagerGrpcAsyncIOTransport, - ], -) -def test_privileged_access_manager_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_entitlement), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_entitlement(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateEntitlementRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivilegedAccessManagerGrpcTransport, - transports.PrivilegedAccessManagerGrpcAsyncIOTransport, - transports.PrivilegedAccessManagerRestTransport, - ], -) -def test_privileged_access_manager_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PrivilegedAccessManagerGrpcTransport, grpc_helpers), - (transports.PrivilegedAccessManagerGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_privileged_access_manager_transport_create_channel( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_entitlement_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + type(client.transport.delete_entitlement), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_entitlement(request=None) - create_channel.assert_called_with( - "privilegedaccessmanager.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="privilegedaccessmanager.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DeleteEntitlementRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivilegedAccessManagerGrpcTransport, - transports.PrivilegedAccessManagerGrpcAsyncIOTransport, - ], -) -def test_privileged_access_manager_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_entitlement_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_entitlement), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_entitlement(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.UpdateEntitlementRequest() -def test_privileged_access_manager_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.PrivilegedAccessManagerRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_privileged_access_manager_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_grants_empty_call_grpc(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_grants), "__call__") as call: + call.return_value = privilegedaccessmanager.ListGrantsResponse() + client.list_grants(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListGrantsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_privileged_access_manager_host_no_port(transport_name): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_grants_empty_call_grpc(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privilegedaccessmanager.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "privilegedaccessmanager.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://privilegedaccessmanager.googleapis.com" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_grants), "__call__") as call: + call.return_value = privilegedaccessmanager.SearchGrantsResponse() + client.search_grants(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_privileged_access_manager_host_with_port(transport_name): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchGrantsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_grant_empty_call_grpc(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privilegedaccessmanager.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "privilegedaccessmanager.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://privilegedaccessmanager.googleapis.com:8000" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_grant), "__call__") as call: + call.return_value = privilegedaccessmanager.Grant() + client.get_grant(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_privileged_access_manager_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = PrivilegedAccessManagerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = PrivilegedAccessManagerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.check_onboarding_status._session - session2 = client2.transport.check_onboarding_status._session - assert session1 != session2 - session1 = client1.transport.list_entitlements._session - session2 = client2.transport.list_entitlements._session - assert session1 != session2 - session1 = client1.transport.search_entitlements._session - session2 = client2.transport.search_entitlements._session - assert session1 != session2 - session1 = client1.transport.get_entitlement._session - session2 = client2.transport.get_entitlement._session - assert session1 != session2 - session1 = client1.transport.create_entitlement._session - session2 = client2.transport.create_entitlement._session - assert session1 != session2 - session1 = client1.transport.delete_entitlement._session - session2 = client2.transport.delete_entitlement._session - assert session1 != session2 - session1 = client1.transport.update_entitlement._session - session2 = client2.transport.update_entitlement._session - assert session1 != session2 - session1 = client1.transport.list_grants._session - session2 = client2.transport.list_grants._session - assert session1 != session2 - session1 = client1.transport.search_grants._session - session2 = client2.transport.search_grants._session - assert session1 != session2 - session1 = client1.transport.get_grant._session - session2 = client2.transport.get_grant._session - assert session1 != session2 - session1 = client1.transport.create_grant._session - session2 = client2.transport.create_grant._session - assert session1 != session2 - session1 = client1.transport.approve_grant._session - session2 = client2.transport.approve_grant._session - assert session1 != session2 - session1 = client1.transport.deny_grant._session - session2 = client2.transport.deny_grant._session - assert session1 != session2 - session1 = client1.transport.revoke_grant._session - session2 = client2.transport.revoke_grant._session - assert session1 != session2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetGrantRequest() + assert args[0] == request_msg -def test_privileged_access_manager_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.PrivilegedAccessManagerGrpcTransport( - host="squid.clam.whelk", - channel=channel, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_grant_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_grant), "__call__") as call: + call.return_value = privilegedaccessmanager.Grant() + client.create_grant(request=None) -def test_privileged_access_manager_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateGrantRequest() - # Check that channel is used if provided. - transport = transports.PrivilegedAccessManagerGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + assert args[0] == request_msg -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivilegedAccessManagerGrpcTransport, - transports.PrivilegedAccessManagerGrpcAsyncIOTransport, - ], -) -def test_privileged_access_manager_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_approve_grant_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.approve_grant), "__call__") as call: + call.return_value = privilegedaccessmanager.Grant() + client.approve_grant(request=None) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ApproveGrantRequest() - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred + assert args[0] == request_msg -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.PrivilegedAccessManagerGrpcTransport, - transports.PrivilegedAccessManagerGrpcAsyncIOTransport, - ], -) -def test_privileged_access_manager_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_deny_grant_empty_call_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.deny_grant), "__call__") as call: + call.return_value = privilegedaccessmanager.Grant() + client.deny_grant(request=None) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DenyGrantRequest() + assert args[0] == request_msg -def test_privileged_access_manager_grpc_lro_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_grant_empty_call_grpc(): client = PrivilegedAccessManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.revoke_grant), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.revoke_grant(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.RevokeGrantRequest() + assert args[0] == request_msg -def test_privileged_access_manager_grpc_lro_async_client(): - client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, +def test_transport_kind_grpc_asyncio(): + transport = PrivilegedAccessManagerAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + assert transport.kind == "grpc_asyncio" -def test_entitlement_path(): - project = "squid" - location = "clam" - entitlement = "whelk" - expected = ( - "projects/{project}/locations/{location}/entitlements/{entitlement}".format( - project=project, - location=location, - entitlement=entitlement, - ) - ) - actual = PrivilegedAccessManagerClient.entitlement_path( - project, location, entitlement +def test_initialize_client_w_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - assert expected == actual - - -def test_parse_entitlement_path(): - expected = { - "project": "octopus", - "location": "oyster", - "entitlement": "nudibranch", - } - path = PrivilegedAccessManagerClient.entitlement_path(**expected) - - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_entitlement_path(path) - assert expected == actual + assert client is not None -def test_grant_path(): - project = "cuttlefish" - location = "mussel" - entitlement = "winkle" - grant = "nautilus" - expected = "projects/{project}/locations/{location}/entitlements/{entitlement}/grants/{grant}".format( - project=project, - location=location, - entitlement=entitlement, - grant=grant, - ) - actual = PrivilegedAccessManagerClient.grant_path( - project, location, entitlement, grant +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_check_onboarding_status_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_onboarding_status), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.CheckOnboardingStatusResponse( + service_account="service_account_value", + ) + ) + await client.check_onboarding_status(request=None) -def test_parse_grant_path(): - expected = { - "project": "scallop", - "location": "abalone", - "entitlement": "squid", - "grant": "clam", - } - path = PrivilegedAccessManagerClient.grant_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CheckOnboardingStatusRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_grant_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_entitlements_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = PrivilegedAccessManagerClient.common_billing_account_path(billing_account) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_entitlements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.ListEntitlementsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_entitlements(request=None) -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = PrivilegedAccessManagerClient.common_billing_account_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListEntitlementsRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_common_billing_account_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_entitlements_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = PrivilegedAccessManagerClient.common_folder_path(folder) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_entitlements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.SearchEntitlementsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_entitlements(request=None) -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = PrivilegedAccessManagerClient.common_folder_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchEntitlementsRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_common_folder_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_entitlement_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = PrivilegedAccessManagerClient.common_organization_path(organization) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_entitlement), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.Entitlement( + name="name_value", + state=privilegedaccessmanager.Entitlement.State.CREATING, + etag="etag_value", + ) + ) + await client.get_entitlement(request=None) -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = PrivilegedAccessManagerClient.common_organization_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetEntitlementRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_common_organization_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_entitlement_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = PrivilegedAccessManagerClient.common_project_path(project) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_entitlement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_entitlement(request=None) -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = PrivilegedAccessManagerClient.common_project_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateEntitlementRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_common_project_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_entitlement_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = PrivilegedAccessManagerClient.common_location_path(project, location) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_entitlement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_entitlement(request=None) -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = PrivilegedAccessManagerClient.common_location_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DeleteEntitlementRequest() - # Check that the path construction is reversible. - actual = PrivilegedAccessManagerClient.parse_common_location_path(path) - assert expected == actual + assert args[0] == request_msg -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_entitlement_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + # Mock the actual call, and fake the request. with mock.patch.object( - transports.PrivilegedAccessManagerTransport, "_prep_wrapped_messages" - ) as prep: - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + type(client.transport.update_entitlement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - prep.assert_called_once_with(client_info) + await client.update_entitlement(request=None) - with mock.patch.object( - transports.PrivilegedAccessManagerTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = PrivilegedAccessManagerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.UpdateEntitlementRequest() + + assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_list_grants_empty_call_grpc_asyncio(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_grants), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.ListGrantsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_grants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListGrantsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_grants_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_grants), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.SearchGrantsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_grants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchGrantsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_grant_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # 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_location(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_grant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + ) + await client.get_grant(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetGrantRequest() -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.GetLocationRequest, - dict, - ], -) -def test_get_location_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_grant_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - request_init = {"name": "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 = locations_pb2.Location() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_grant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + ) + await client.create_grant(request=None) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateGrantRequest() - response = client.get_location(request) + assert args[0] == request_msg - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_approve_grant_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.approve_grant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + ) + await client.approve_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ApproveGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_deny_grant_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.deny_grant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + ) + await client.deny_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DenyGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_revoke_grant_empty_call_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.revoke_grant), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.revoke_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.RevokeGrantRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PrivilegedAccessManagerClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_check_onboarding_status_rest_bad_request( + request_type=privilegedaccessmanager.CheckOnboardingStatusRequest, ): client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.list_locations(request) + client.check_onboarding_status(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.ListLocationsRequest, + privilegedaccessmanager.CheckOnboardingStatusRequest, dict, ], ) -def test_list_locations_rest(request_type): +def test_check_onboarding_status_rest_call_success(request_type): client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - request_init = {"name": "projects/sample1"} + + # 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 = locations_pb2.ListLocationsResponse() + return_value = privilegedaccessmanager.CheckOnboardingStatusResponse( + service_account="service_account_value", + ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + # Convert return value to protobuf type + return_value = privilegedaccessmanager.CheckOnboardingStatusResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - - response = client.list_locations(request) + response = client.check_onboarding_status(request) # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + assert isinstance(response, privilegedaccessmanager.CheckOnboardingStatusResponse) + assert response.service_account == "service_account_value" -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = PrivilegedAccessManagerClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_check_onboarding_status_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), ) + client = PrivilegedAccessManagerClient(transport=transport) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, + "post_check_onboarding_status", + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_check_onboarding_status" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.CheckOnboardingStatusRequest.pb( + privilegedaccessmanager.CheckOnboardingStatusRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # 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() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.CheckOnboardingStatusResponse.to_json( + privilegedaccessmanager.CheckOnboardingStatusResponse() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.CheckOnboardingStatusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.CheckOnboardingStatusResponse() + + client.check_onboarding_status( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_entitlements_rest_bad_request( + request_type=privilegedaccessmanager.ListEntitlementsRequest, +): + client = PrivilegedAccessManagerClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.delete_operation(request) + client.list_entitlements(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.ListEntitlementsRequest, + dict, + ], +) +def test_list_entitlements_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + 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 = privilegedaccessmanager.ListEntitlementsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.ListEntitlementsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_entitlements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEntitlementsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_entitlements_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_list_entitlements" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_list_entitlements" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.ListEntitlementsRequest.pb( + privilegedaccessmanager.ListEntitlementsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.ListEntitlementsResponse.to_json( + privilegedaccessmanager.ListEntitlementsResponse() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.ListEntitlementsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.ListEntitlementsResponse() + + client.list_entitlements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_entitlements_rest_bad_request( + request_type=privilegedaccessmanager.SearchEntitlementsRequest, +): + client = PrivilegedAccessManagerClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_entitlements(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.SearchEntitlementsRequest, + dict, + ], +) +def test_search_entitlements_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + 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 = privilegedaccessmanager.SearchEntitlementsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.SearchEntitlementsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_entitlements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchEntitlementsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_entitlements_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_search_entitlements" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_search_entitlements" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.SearchEntitlementsRequest.pb( + privilegedaccessmanager.SearchEntitlementsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.SearchEntitlementsResponse.to_json( + privilegedaccessmanager.SearchEntitlementsResponse() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.SearchEntitlementsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.SearchEntitlementsResponse() + + client.search_entitlements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_entitlement_rest_bad_request( + request_type=privilegedaccessmanager.GetEntitlementRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_entitlement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.GetEntitlementRequest, + dict, + ], +) +def test_get_entitlement_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.Entitlement( + name="name_value", + state=privilegedaccessmanager.Entitlement.State.CREATING, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.Entitlement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_entitlement(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, privilegedaccessmanager.Entitlement) + assert response.name == "name_value" + assert response.state == privilegedaccessmanager.Entitlement.State.CREATING + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_entitlement_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_get_entitlement" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_get_entitlement" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.GetEntitlementRequest.pb( + privilegedaccessmanager.GetEntitlementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.Entitlement.to_json( + privilegedaccessmanager.Entitlement() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.GetEntitlementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.Entitlement() + + client.get_entitlement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_entitlement_rest_bad_request( + request_type=privilegedaccessmanager.CreateEntitlementRequest, +): + client = PrivilegedAccessManagerClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_entitlement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.CreateEntitlementRequest, + dict, + ], +) +def test_create_entitlement_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["entitlement"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "eligible_users": [{"principals": ["principals_value1", "principals_value2"]}], + "approval_workflow": { + "manual_approvals": { + "require_approver_justification": True, + "steps": [ + { + "approvers": {}, + "approvals_needed": 1692, + "approver_email_recipients": [ + "approver_email_recipients_value1", + "approver_email_recipients_value2", + ], + } + ], + } + }, + "privileged_access": { + "gcp_iam_access": { + "resource_type": "resource_type_value", + "resource": "resource_value", + "role_bindings": [ + { + "role": "role_value", + "condition_expression": "condition_expression_value", + } + ], + } + }, + "max_request_duration": {"seconds": 751, "nanos": 543}, + "state": 1, + "requester_justification_config": {"not_mandatory": {}, "unstructured": {}}, + "additional_notification_targets": { + "admin_email_recipients": [ + "admin_email_recipients_value1", + "admin_email_recipients_value2", + ], + "requester_email_recipients": [ + "requester_email_recipients_value1", + "requester_email_recipients_value2", + ], + }, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = privilegedaccessmanager.CreateEntitlementRequest.meta.fields[ + "entitlement" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["entitlement"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["entitlement"][field])): + del request_init["entitlement"][field][i][subfield] + else: + del request_init["entitlement"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_entitlement(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_entitlement_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "post_create_entitlement" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_create_entitlement" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.CreateEntitlementRequest.pb( + privilegedaccessmanager.CreateEntitlementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = privilegedaccessmanager.CreateEntitlementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_entitlement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_entitlement_rest_bad_request( + request_type=privilegedaccessmanager.DeleteEntitlementRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_entitlement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.DeleteEntitlementRequest, + dict, + ], +) +def test_delete_entitlement_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/entitlements/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_entitlement(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_entitlement_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "post_delete_entitlement" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_delete_entitlement" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.DeleteEntitlementRequest.pb( + privilegedaccessmanager.DeleteEntitlementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = privilegedaccessmanager.DeleteEntitlementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_entitlement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_entitlement_rest_bad_request( + request_type=privilegedaccessmanager.UpdateEntitlementRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "entitlement": { + "name": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_entitlement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.UpdateEntitlementRequest, + dict, + ], +) +def test_update_entitlement_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "entitlement": { + "name": "projects/sample1/locations/sample2/entitlements/sample3" + } + } + request_init["entitlement"] = { + "name": "projects/sample1/locations/sample2/entitlements/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "eligible_users": [{"principals": ["principals_value1", "principals_value2"]}], + "approval_workflow": { + "manual_approvals": { + "require_approver_justification": True, + "steps": [ + { + "approvers": {}, + "approvals_needed": 1692, + "approver_email_recipients": [ + "approver_email_recipients_value1", + "approver_email_recipients_value2", + ], + } + ], + } + }, + "privileged_access": { + "gcp_iam_access": { + "resource_type": "resource_type_value", + "resource": "resource_value", + "role_bindings": [ + { + "role": "role_value", + "condition_expression": "condition_expression_value", + } + ], + } + }, + "max_request_duration": {"seconds": 751, "nanos": 543}, + "state": 1, + "requester_justification_config": {"not_mandatory": {}, "unstructured": {}}, + "additional_notification_targets": { + "admin_email_recipients": [ + "admin_email_recipients_value1", + "admin_email_recipients_value2", + ], + "requester_email_recipients": [ + "requester_email_recipients_value1", + "requester_email_recipients_value2", + ], + }, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = privilegedaccessmanager.UpdateEntitlementRequest.meta.fields[ + "entitlement" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["entitlement"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["entitlement"][field])): + del request_init["entitlement"][field][i][subfield] + else: + del request_init["entitlement"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_entitlement(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_entitlement_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "post_update_entitlement" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_update_entitlement" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.UpdateEntitlementRequest.pb( + privilegedaccessmanager.UpdateEntitlementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = privilegedaccessmanager.UpdateEntitlementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_entitlement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_grants_rest_bad_request( + request_type=privilegedaccessmanager.ListGrantsRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_grants(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.ListGrantsRequest, + dict, + ], +) +def test_list_grants_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.ListGrantsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.ListGrantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_grants(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGrantsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_grants_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_list_grants" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_list_grants" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.ListGrantsRequest.pb( + privilegedaccessmanager.ListGrantsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.ListGrantsResponse.to_json( + privilegedaccessmanager.ListGrantsResponse() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.ListGrantsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.ListGrantsResponse() + + client.list_grants( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_grants_rest_bad_request( + request_type=privilegedaccessmanager.SearchGrantsRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_grants(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.SearchGrantsRequest, + dict, + ], +) +def test_search_grants_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = privilegedaccessmanager.SearchGrantsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.SearchGrantsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_grants(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchGrantsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_grants_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_search_grants" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_search_grants" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.SearchGrantsRequest.pb( + privilegedaccessmanager.SearchGrantsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.SearchGrantsResponse.to_json( + privilegedaccessmanager.SearchGrantsResponse() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.SearchGrantsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.SearchGrantsResponse() + + client.search_grants( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_grant_rest_bad_request( + request_type=privilegedaccessmanager.GetGrantRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_grant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.GetGrantRequest, + dict, + ], +) +def test_get_grant_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.Grant.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_grant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, privilegedaccessmanager.Grant) + assert response.name == "name_value" + assert response.requester == "requester_value" + assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED + assert response.additional_email_recipients == ["additional_email_recipients_value"] + assert response.externally_modified is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_grant_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_get_grant" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_get_grant" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.GetGrantRequest.pb( + privilegedaccessmanager.GetGrantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.Grant.to_json( + privilegedaccessmanager.Grant() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.GetGrantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.Grant() + + client.get_grant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_grant_rest_bad_request( + request_type=privilegedaccessmanager.CreateGrantRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_grant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.CreateGrantRequest, + dict, + ], +) +def test_create_grant_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/entitlements/sample3"} + request_init["grant"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "requester": "requester_value", + "requested_duration": {"seconds": 751, "nanos": 543}, + "justification": { + "unstructured_justification": "unstructured_justification_value" + }, + "state": 1, + "timeline": { + "events": [ + { + "requested": {"expire_time": {}}, + "approved": {"reason": "reason_value", "actor": "actor_value"}, + "denied": {"reason": "reason_value", "actor": "actor_value"}, + "revoked": {"reason": "reason_value", "actor": "actor_value"}, + "scheduled": {"scheduled_activation_time": {}}, + "activated": {}, + "activation_failed": { + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + } + }, + "expired": {}, + "ended": {}, + "externally_modified": {}, + "event_time": {}, + } + ] + }, + "privileged_access": { + "gcp_iam_access": { + "resource_type": "resource_type_value", + "resource": "resource_value", + "role_bindings": [ + { + "role": "role_value", + "condition_expression": "condition_expression_value", + } + ], + } + }, + "audit_trail": {"access_grant_time": {}, "access_remove_time": {}}, + "additional_email_recipients": [ + "additional_email_recipients_value1", + "additional_email_recipients_value2", + ], + "externally_modified": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = privilegedaccessmanager.CreateGrantRequest.meta.fields["grant"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["grant"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["grant"][field])): + del request_init["grant"][field][i][subfield] + else: + del request_init["grant"][field][subfield] + 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 = privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.Grant.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_grant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, privilegedaccessmanager.Grant) + assert response.name == "name_value" + assert response.requester == "requester_value" + assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED + assert response.additional_email_recipients == ["additional_email_recipients_value"] + assert response.externally_modified is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_grant_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_create_grant" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_create_grant" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.CreateGrantRequest.pb( + privilegedaccessmanager.CreateGrantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.Grant.to_json( + privilegedaccessmanager.Grant() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.CreateGrantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.Grant() + + client.create_grant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_approve_grant_rest_bad_request( + request_type=privilegedaccessmanager.ApproveGrantRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.approve_grant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.ApproveGrantRequest, + dict, + ], +) +def test_approve_grant_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.Grant.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.approve_grant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, privilegedaccessmanager.Grant) + assert response.name == "name_value" + assert response.requester == "requester_value" + assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED + assert response.additional_email_recipients == ["additional_email_recipients_value"] + assert response.externally_modified is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_approve_grant_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_approve_grant" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_approve_grant" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.ApproveGrantRequest.pb( + privilegedaccessmanager.ApproveGrantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.Grant.to_json( + privilegedaccessmanager.Grant() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.ApproveGrantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.Grant() + + client.approve_grant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deny_grant_rest_bad_request( + request_type=privilegedaccessmanager.DenyGrantRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.deny_grant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.DenyGrantRequest, + dict, + ], +) +def test_deny_grant_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = privilegedaccessmanager.Grant( + name="name_value", + requester="requester_value", + state=privilegedaccessmanager.Grant.State.APPROVAL_AWAITED, + additional_email_recipients=["additional_email_recipients_value"], + externally_modified=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = privilegedaccessmanager.Grant.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.deny_grant(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, privilegedaccessmanager.Grant) + assert response.name == "name_value" + assert response.requester == "requester_value" + assert response.state == privilegedaccessmanager.Grant.State.APPROVAL_AWAITED + assert response.additional_email_recipients == ["additional_email_recipients_value"] + assert response.externally_modified is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deny_grant_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(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.PrivilegedAccessManagerRestInterceptor, "post_deny_grant" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_deny_grant" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.DenyGrantRequest.pb( + privilegedaccessmanager.DenyGrantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = privilegedaccessmanager.Grant.to_json( + privilegedaccessmanager.Grant() + ) + req.return_value.content = return_value + + request = privilegedaccessmanager.DenyGrantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = privilegedaccessmanager.Grant() + + client.deny_grant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_revoke_grant_rest_bad_request( + request_type=privilegedaccessmanager.RevokeGrantRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.revoke_grant(request) + + +@pytest.mark.parametrize( + "request_type", + [ + privilegedaccessmanager.RevokeGrantRequest, + dict, + ], +) +def test_revoke_grant_rest_call_success(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/entitlements/sample3/grants/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.revoke_grant(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_revoke_grant_rest_interceptors(null_interceptor): + transport = transports.PrivilegedAccessManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PrivilegedAccessManagerRestInterceptor(), + ) + client = PrivilegedAccessManagerClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "post_revoke_grant" + ) as post, mock.patch.object( + transports.PrivilegedAccessManagerRestInterceptor, "pre_revoke_grant" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = privilegedaccessmanager.RevokeGrantRequest.pb( + privilegedaccessmanager.RevokeGrantRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = privilegedaccessmanager.RevokeGrantRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.revoke_grant( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_check_onboarding_status_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_onboarding_status), "__call__" + ) as call: + client.check_onboarding_status(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CheckOnboardingStatusRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_entitlements_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_entitlements), "__call__" + ) as call: + client.list_entitlements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListEntitlementsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_entitlements_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_entitlements), "__call__" + ) as call: + client.search_entitlements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchEntitlementsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_entitlement_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_entitlement), "__call__") as call: + client.get_entitlement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetEntitlementRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_entitlement_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_entitlement), "__call__" + ) as call: + client.create_entitlement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateEntitlementRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_entitlement_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_entitlement), "__call__" + ) as call: + client.delete_entitlement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DeleteEntitlementRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_entitlement_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_entitlement), "__call__" + ) as call: + client.update_entitlement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.UpdateEntitlementRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_grants_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_grants), "__call__") as call: + client.list_grants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ListGrantsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_grants_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_grants), "__call__") as call: + client.search_grants(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.SearchGrantsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_grant_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_grant), "__call__") as call: + client.get_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.GetGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_grant_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_grant), "__call__") as call: + client.create_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.CreateGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_approve_grant_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.approve_grant), "__call__") as call: + client.approve_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.ApproveGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_deny_grant_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.deny_grant), "__call__") as call: + client.deny_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.DenyGrantRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_revoke_grant_empty_call_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.revoke_grant), "__call__") as call: + client.revoke_grant(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = privilegedaccessmanager.RevokeGrantRequest() + + assert args[0] == request_msg + + +def test_privileged_access_manager_rest_lro_client(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PrivilegedAccessManagerGrpcTransport, + ) + + +def test_privileged_access_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PrivilegedAccessManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_privileged_access_manager_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PrivilegedAccessManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "check_onboarding_status", + "list_entitlements", + "search_entitlements", + "get_entitlement", + "create_entitlement", + "delete_entitlement", + "update_entitlement", + "list_grants", + "search_grants", + "get_grant", + "create_grant", + "approve_grant", + "deny_grant", + "revoke_grant", + "get_location", + "list_locations", + "get_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_privileged_access_manager_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.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PrivilegedAccessManagerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_privileged_access_manager_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.privilegedaccessmanager_v1.services.privileged_access_manager.transports.PrivilegedAccessManagerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PrivilegedAccessManagerTransport() + adc.assert_called_once() + + +def test_privileged_access_manager_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PrivilegedAccessManagerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivilegedAccessManagerGrpcTransport, + transports.PrivilegedAccessManagerGrpcAsyncIOTransport, + ], +) +def test_privileged_access_manager_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivilegedAccessManagerGrpcTransport, + transports.PrivilegedAccessManagerGrpcAsyncIOTransport, + transports.PrivilegedAccessManagerRestTransport, + ], +) +def test_privileged_access_manager_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PrivilegedAccessManagerGrpcTransport, grpc_helpers), + (transports.PrivilegedAccessManagerGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_privileged_access_manager_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "privilegedaccessmanager.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="privilegedaccessmanager.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivilegedAccessManagerGrpcTransport, + transports.PrivilegedAccessManagerGrpcAsyncIOTransport, + ], +) +def test_privileged_access_manager_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_privileged_access_manager_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.PrivilegedAccessManagerRestTransport( + 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_privileged_access_manager_host_no_port(transport_name): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privilegedaccessmanager.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privilegedaccessmanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privilegedaccessmanager.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_privileged_access_manager_host_with_port(transport_name): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privilegedaccessmanager.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privilegedaccessmanager.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privilegedaccessmanager.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_privileged_access_manager_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PrivilegedAccessManagerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PrivilegedAccessManagerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.check_onboarding_status._session + session2 = client2.transport.check_onboarding_status._session + assert session1 != session2 + session1 = client1.transport.list_entitlements._session + session2 = client2.transport.list_entitlements._session + assert session1 != session2 + session1 = client1.transport.search_entitlements._session + session2 = client2.transport.search_entitlements._session + assert session1 != session2 + session1 = client1.transport.get_entitlement._session + session2 = client2.transport.get_entitlement._session + assert session1 != session2 + session1 = client1.transport.create_entitlement._session + session2 = client2.transport.create_entitlement._session + assert session1 != session2 + session1 = client1.transport.delete_entitlement._session + session2 = client2.transport.delete_entitlement._session + assert session1 != session2 + session1 = client1.transport.update_entitlement._session + session2 = client2.transport.update_entitlement._session + assert session1 != session2 + session1 = client1.transport.list_grants._session + session2 = client2.transport.list_grants._session + assert session1 != session2 + session1 = client1.transport.search_grants._session + session2 = client2.transport.search_grants._session + assert session1 != session2 + session1 = client1.transport.get_grant._session + session2 = client2.transport.get_grant._session + assert session1 != session2 + session1 = client1.transport.create_grant._session + session2 = client2.transport.create_grant._session + assert session1 != session2 + session1 = client1.transport.approve_grant._session + session2 = client2.transport.approve_grant._session + assert session1 != session2 + session1 = client1.transport.deny_grant._session + session2 = client2.transport.deny_grant._session + assert session1 != session2 + session1 = client1.transport.revoke_grant._session + session2 = client2.transport.revoke_grant._session + assert session1 != session2 + + +def test_privileged_access_manager_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PrivilegedAccessManagerGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_privileged_access_manager_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PrivilegedAccessManagerGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivilegedAccessManagerGrpcTransport, + transports.PrivilegedAccessManagerGrpcAsyncIOTransport, + ], +) +def test_privileged_access_manager_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.PrivilegedAccessManagerGrpcTransport, + transports.PrivilegedAccessManagerGrpcAsyncIOTransport, + ], +) +def test_privileged_access_manager_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_privileged_access_manager_grpc_lro_client(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_privileged_access_manager_grpc_lro_async_client(): + client = PrivilegedAccessManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_entitlement_path(): + project = "squid" + location = "clam" + entitlement = "whelk" + expected = ( + "projects/{project}/locations/{location}/entitlements/{entitlement}".format( + project=project, + location=location, + entitlement=entitlement, + ) + ) + actual = PrivilegedAccessManagerClient.entitlement_path( + project, location, entitlement + ) + assert expected == actual + + +def test_parse_entitlement_path(): + expected = { + "project": "octopus", + "location": "oyster", + "entitlement": "nudibranch", + } + path = PrivilegedAccessManagerClient.entitlement_path(**expected) + + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_entitlement_path(path) + assert expected == actual + + +def test_grant_path(): + project = "cuttlefish" + location = "mussel" + entitlement = "winkle" + grant = "nautilus" + expected = "projects/{project}/locations/{location}/entitlements/{entitlement}/grants/{grant}".format( + project=project, + location=location, + entitlement=entitlement, + grant=grant, + ) + actual = PrivilegedAccessManagerClient.grant_path( + project, location, entitlement, grant + ) + assert expected == actual + + +def test_parse_grant_path(): + expected = { + "project": "scallop", + "location": "abalone", + "entitlement": "squid", + "grant": "clam", + } + path = PrivilegedAccessManagerClient.grant_path(**expected) + + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_grant_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = PrivilegedAccessManagerClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = PrivilegedAccessManagerClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = PrivilegedAccessManagerClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = PrivilegedAccessManagerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_common_folder_path(path) + assert expected == actual -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = PrivilegedAccessManagerClient.common_organization_path(organization) + assert expected == actual - # 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_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = PrivilegedAccessManagerClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = PrivilegedAccessManagerClient.common_project_path(project) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = PrivilegedAccessManagerClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_common_project_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = PrivilegedAccessManagerClient.common_location_path(project, location) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = PrivilegedAccessManagerClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = PrivilegedAccessManagerClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.list_operations(request) + with mock.patch.object( + transports.PrivilegedAccessManagerTransport, "_prep_wrapped_messages" + ) as prep: + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + with mock.patch.object( + transports.PrivilegedAccessManagerTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PrivilegedAccessManagerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -12858,7 +13193,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -12911,7 +13246,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -12956,7 +13291,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -12997,7 +13332,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13052,7 +13387,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13099,7 +13434,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -13142,7 +13477,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13197,7 +13532,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13244,7 +13579,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -13287,7 +13622,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13342,7 +13677,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13389,7 +13724,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -13432,7 +13767,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -13487,7 +13822,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials() + credentials=async_anonymous_credentials() ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -13534,7 +13869,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = PrivilegedAccessManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -13550,22 +13885,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = PrivilegedAccessManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = PrivilegedAccessManagerAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = PrivilegedAccessManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/README.rst b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/README.rst new file mode 100644 index 000000000000..3de49564f5ce --- /dev/null +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PublicCertificateAuthorityServiceTransport` is the ABC for all transports. +- public child `PublicCertificateAuthorityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PublicCertificateAuthorityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePublicCertificateAuthorityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PublicCertificateAuthorityServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/grpc_asyncio.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/grpc_asyncio.py index 257a5bd257ae..6232b617e963 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -276,15 +280,24 @@ def create_external_account_key( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_external_account_key: gapic_v1.method_async.wrap_method( + self.create_external_account_key: self._wrap_method( self.create_external_account_key, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PublicCertificateAuthorityServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest.py index 0299ce0045e2..936022b91667 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.security.publicca_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePublicCertificateAuthorityServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.security.publicca_v1.types import resources, service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PublicCertificateAuthorityServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -109,9 +106,9 @@ class PublicCertificateAuthorityServiceRestStub: class PublicCertificateAuthorityServiceRestTransport( - PublicCertificateAuthorityServiceTransport + _BasePublicCertificateAuthorityServiceRestTransport ): - """REST backend transport for PublicCertificateAuthorityService. + """REST backend synchronous transport for PublicCertificateAuthorityService. Manages the resources required for ACME `external account binding `__ for @@ -122,7 +119,6 @@ class PublicCertificateAuthorityServiceRestTransport( and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -176,21 +172,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -203,19 +190,37 @@ def __init__( ) self._prep_wrapped_messages(client_info) - class _CreateExternalAccountKey(PublicCertificateAuthorityServiceRestStub): + class _CreateExternalAccountKey( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey, + PublicCertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateExternalAccountKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "PublicCertificateAuthorityServiceRestTransport.CreateExternalAccountKey" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -248,47 +253,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/externalAccountKeys", - "body": "external_account_key", - }, - ] + http_options = ( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_http_options() + ) request, metadata = self._interceptor.pre_create_external_account_key( request, metadata ) - pb_request = service.CreateExternalAccountKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PublicCertificateAuthorityServiceRestTransport._CreateExternalAccountKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest_base.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest_base.py new file mode 100644 index 000000000000..a29d676057c2 --- /dev/null +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1/services/public_certificate_authority_service/transports/rest_base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.security.publicca_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO, PublicCertificateAuthorityServiceTransport + + +class _BasePublicCertificateAuthorityServiceRestTransport( + PublicCertificateAuthorityServiceTransport +): + """Base REST backend transport for PublicCertificateAuthorityService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "publicca.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'publicca.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateExternalAccountKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/externalAccountKeys", + "body": "external_account_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateExternalAccountKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePublicCertificateAuthorityServiceRestTransport",) diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/README.rst b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/README.rst new file mode 100644 index 000000000000..3de49564f5ce --- /dev/null +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PublicCertificateAuthorityServiceTransport` is the ABC for all transports. +- public child `PublicCertificateAuthorityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PublicCertificateAuthorityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePublicCertificateAuthorityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PublicCertificateAuthorityServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/grpc_asyncio.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/grpc_asyncio.py index 6cfd29b66bee..5ff69f91ef04 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -276,15 +280,24 @@ def create_external_account_key( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_external_account_key: gapic_v1.method_async.wrap_method( + self.create_external_account_key: self._wrap_method( self.create_external_account_key, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PublicCertificateAuthorityServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest.py index bf86e79d66ef..41ccde110eca 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.security.publicca_v1beta1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePublicCertificateAuthorityServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.security.publicca_v1beta1.types import resources, service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PublicCertificateAuthorityServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -109,9 +106,9 @@ class PublicCertificateAuthorityServiceRestStub: class PublicCertificateAuthorityServiceRestTransport( - PublicCertificateAuthorityServiceTransport + _BasePublicCertificateAuthorityServiceRestTransport ): - """REST backend transport for PublicCertificateAuthorityService. + """REST backend synchronous transport for PublicCertificateAuthorityService. Manages the resources required for ACME `external account binding `__ for @@ -122,7 +119,6 @@ class PublicCertificateAuthorityServiceRestTransport( and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -176,21 +172,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -203,19 +190,37 @@ def __init__( ) self._prep_wrapped_messages(client_info) - class _CreateExternalAccountKey(PublicCertificateAuthorityServiceRestStub): + class _CreateExternalAccountKey( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey, + PublicCertificateAuthorityServiceRestStub, + ): def __hash__(self): - return hash("CreateExternalAccountKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "PublicCertificateAuthorityServiceRestTransport.CreateExternalAccountKey" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -248,47 +253,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/externalAccountKeys", - "body": "external_account_key", - }, - ] + http_options = ( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_http_options() + ) request, metadata = self._interceptor.pre_create_external_account_key( request, metadata ) - pb_request = service.CreateExternalAccountKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PublicCertificateAuthorityServiceRestTransport._CreateExternalAccountKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest_base.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest_base.py new file mode 100644 index 000000000000..d3b6d537a3c9 --- /dev/null +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/services/public_certificate_authority_service/transports/rest_base.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.security.publicca_v1beta1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO, PublicCertificateAuthorityServiceTransport + + +class _BasePublicCertificateAuthorityServiceRestTransport( + PublicCertificateAuthorityServiceTransport +): + """Base REST backend transport for PublicCertificateAuthorityService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "publicca.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'publicca.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateExternalAccountKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/externalAccountKeys", + "body": "external_account_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateExternalAccountKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublicCertificateAuthorityServiceRestTransport._BaseCreateExternalAccountKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePublicCertificateAuthorityServiceRestTransport",) diff --git a/packages/google-cloud-public-ca/setup.py b/packages/google-cloud-public-ca/setup.py index c2c6eef7b56f..f67c1361a0fe 100644 --- a/packages/google-cloud-public-ca/setup.py +++ b/packages/google-cloud-public-ca/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-security-publicca" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1/test_public_certificate_authority_service.py b/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1/test_public_certificate_authority_service.py index a8149b091358..a5bdbae4b2c5 100644 --- a/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1/test_public_certificate_authority_service.py +++ b/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1/test_public_certificate_authority_service.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.security.publicca_v1.services.public_certificate_authority_service import ( PublicCertificateAuthorityServiceAsyncClient, PublicCertificateAuthorityServiceClient, @@ -51,10 +60,24 @@ from google.cloud.security.publicca_v1.types import resources, service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1264,27 +1287,6 @@ def test_create_external_account_key(request_type, transport: str = "grpc"): assert response.b64_mac_key == b"b64_mac_key_blob" -def test_create_external_account_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_external_account_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_external_account_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateExternalAccountKeyRequest() - - def test_create_external_account_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1355,33 +1357,6 @@ def test_create_external_account_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_external_account_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_external_account_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ExternalAccountKey( - name="name_value", - key_id="key_id_value", - b64_mac_key=b"b64_mac_key_blob", - ) - ) - response = await client.create_external_account_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateExternalAccountKeyRequest() - - @pytest.mark.asyncio async def test_create_external_account_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1390,7 +1365,7 @@ async def test_create_external_account_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1430,7 +1405,7 @@ async def test_create_external_account_key_async( request_type=service.CreateExternalAccountKeyRequest, ): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1504,7 +1479,7 @@ def test_create_external_account_key_field_headers(): @pytest.mark.asyncio async def test_create_external_account_key_field_headers_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1583,7 +1558,7 @@ def test_create_external_account_key_flattened_error(): @pytest.mark.asyncio async def test_create_external_account_key_flattened_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1618,7 +1593,7 @@ async def test_create_external_account_key_flattened_async(): @pytest.mark.asyncio async def test_create_external_account_key_flattened_error_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1631,126 +1606,6 @@ async def test_create_external_account_key_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - service.CreateExternalAccountKeyRequest, - dict, - ], -) -def test_create_external_account_key_rest(request_type): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["external_account_key"] = { - "name": "name_value", - "key_id": "key_id_value", - "b64_mac_key": b"b64_mac_key_blob", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateExternalAccountKeyRequest.meta.fields[ - "external_account_key" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "external_account_key" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["external_account_key"][field])): - del request_init["external_account_key"][field][i][subfield] - else: - del request_init["external_account_key"][field][subfield] - 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 = resources.ExternalAccountKey( - name="name_value", - key_id="key_id_value", - b64_mac_key=b"b64_mac_key_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ExternalAccountKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_external_account_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ExternalAccountKey) - assert response.name == "name_value" - assert response.key_id == "key_id_value" - assert response.b64_mac_key == b"b64_mac_key_blob" - - def test_create_external_account_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1884,120 +1739,37 @@ def test_create_external_account_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_external_account_key_rest_interceptors(null_interceptor): - transport = transports.PublicCertificateAuthorityServiceRestTransport( +def test_create_external_account_key_rest_flattened(): + client = PublicCertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PublicCertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = PublicCertificateAuthorityServiceClient(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.PublicCertificateAuthorityServiceRestInterceptor, - "post_create_external_account_key", - ) as post, mock.patch.object( - transports.PublicCertificateAuthorityServiceRestInterceptor, - "pre_create_external_account_key", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateExternalAccountKeyRequest.pb( - service.CreateExternalAccountKeyRequest() - ) - 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 = resources.ExternalAccountKey.to_json( - resources.ExternalAccountKey() - ) + # 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 = resources.ExternalAccountKey() - request = service.CreateExternalAccountKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ExternalAccountKey() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - client.create_external_account_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + external_account_key=resources.ExternalAccountKey(name="name_value"), ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ExternalAccountKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_create_external_account_key_rest_bad_request( - transport: str = "rest", request_type=service.CreateExternalAccountKeyRequest -): - client = PublicCertificateAuthorityServiceClient( - 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.create_external_account_key(request) - - -def test_create_external_account_key_rest_flattened(): - client = PublicCertificateAuthorityServiceClient( - 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 = resources.ExternalAccountKey() - - # 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", - external_account_key=resources.ExternalAccountKey(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ExternalAccountKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_external_account_key(**mock_args) + client.create_external_account_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2026,12 +1798,6 @@ def test_create_external_account_key_rest_flattened_error(transport: str = "rest ) -def test_create_external_account_key_rest_error(): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PublicCertificateAuthorityServiceGrpcTransport( @@ -2124,20 +1890,325 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = PublicCertificateAuthorityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_external_account_key_empty_call_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + call.return_value = resources.ExternalAccountKey() + client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PublicCertificateAuthorityServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PublicCertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_external_account_key_empty_call_grpc_asyncio(): + client = PublicCertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ExternalAccountKey( + name="name_value", + key_id="key_id_value", + b64_mac_key=b"b64_mac_key_blob", + ) + ) + await client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PublicCertificateAuthorityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_external_account_key_rest_bad_request( + request_type=service.CreateExternalAccountKeyRequest, +): + client = PublicCertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_external_account_key(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + service.CreateExternalAccountKeyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PublicCertificateAuthorityServiceClient.get_transport_class( - transport_name - )( +def test_create_external_account_key_rest_call_success(request_type): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["external_account_key"] = { + "name": "name_value", + "key_id": "key_id_value", + "b64_mac_key": b"b64_mac_key_blob", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateExternalAccountKeyRequest.meta.fields[ + "external_account_key" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "external_account_key" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["external_account_key"][field])): + del request_init["external_account_key"][field][i][subfield] + else: + del request_init["external_account_key"][field][subfield] + 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 = resources.ExternalAccountKey( + name="name_value", + key_id="key_id_value", + b64_mac_key=b"b64_mac_key_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ExternalAccountKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_external_account_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ExternalAccountKey) + assert response.name == "name_value" + assert response.key_id == "key_id_value" + assert response.b64_mac_key == b"b64_mac_key_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_external_account_key_rest_interceptors(null_interceptor): + transport = transports.PublicCertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PublicCertificateAuthorityServiceRestInterceptor(), + ) + client = PublicCertificateAuthorityServiceClient(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.PublicCertificateAuthorityServiceRestInterceptor, + "post_create_external_account_key", + ) as post, mock.patch.object( + transports.PublicCertificateAuthorityServiceRestInterceptor, + "pre_create_external_account_key", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateExternalAccountKeyRequest.pb( + service.CreateExternalAccountKeyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.ExternalAccountKey.to_json( + resources.ExternalAccountKey() + ) + req.return_value.content = return_value + + request = service.CreateExternalAccountKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ExternalAccountKey() + + client.create_external_account_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_external_account_key_empty_call_rest(): + client = PublicCertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2742,36 +2813,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1beta1/test_public_certificate_authority_service.py b/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1beta1/test_public_certificate_authority_service.py index f40e37aae2df..f1a7ebecac47 100644 --- a/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1beta1/test_public_certificate_authority_service.py +++ b/packages/google-cloud-public-ca/tests/unit/gapic/publicca_v1beta1/test_public_certificate_authority_service.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.security.publicca_v1beta1.services.public_certificate_authority_service import ( PublicCertificateAuthorityServiceAsyncClient, PublicCertificateAuthorityServiceClient, @@ -51,10 +60,24 @@ from google.cloud.security.publicca_v1beta1.types import resources, service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1264,27 +1287,6 @@ def test_create_external_account_key(request_type, transport: str = "grpc"): assert response.b64_mac_key == b"b64_mac_key_blob" -def test_create_external_account_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_external_account_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_external_account_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateExternalAccountKeyRequest() - - def test_create_external_account_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1355,33 +1357,6 @@ def test_create_external_account_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_external_account_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_external_account_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ExternalAccountKey( - name="name_value", - key_id="key_id_value", - b64_mac_key=b"b64_mac_key_blob", - ) - ) - response = await client.create_external_account_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateExternalAccountKeyRequest() - - @pytest.mark.asyncio async def test_create_external_account_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1390,7 +1365,7 @@ async def test_create_external_account_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1430,7 +1405,7 @@ async def test_create_external_account_key_async( request_type=service.CreateExternalAccountKeyRequest, ): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1504,7 +1479,7 @@ def test_create_external_account_key_field_headers(): @pytest.mark.asyncio async def test_create_external_account_key_field_headers_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1583,7 +1558,7 @@ def test_create_external_account_key_flattened_error(): @pytest.mark.asyncio async def test_create_external_account_key_flattened_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1618,7 +1593,7 @@ async def test_create_external_account_key_flattened_async(): @pytest.mark.asyncio async def test_create_external_account_key_flattened_error_async(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1631,126 +1606,6 @@ async def test_create_external_account_key_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - service.CreateExternalAccountKeyRequest, - dict, - ], -) -def test_create_external_account_key_rest(request_type): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["external_account_key"] = { - "name": "name_value", - "key_id": "key_id_value", - "b64_mac_key": b"b64_mac_key_blob", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateExternalAccountKeyRequest.meta.fields[ - "external_account_key" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "external_account_key" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["external_account_key"][field])): - del request_init["external_account_key"][field][i][subfield] - else: - del request_init["external_account_key"][field][subfield] - 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 = resources.ExternalAccountKey( - name="name_value", - key_id="key_id_value", - b64_mac_key=b"b64_mac_key_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ExternalAccountKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_external_account_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ExternalAccountKey) - assert response.name == "name_value" - assert response.key_id == "key_id_value" - assert response.b64_mac_key == b"b64_mac_key_blob" - - def test_create_external_account_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1884,120 +1739,37 @@ def test_create_external_account_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_external_account_key_rest_interceptors(null_interceptor): - transport = transports.PublicCertificateAuthorityServiceRestTransport( +def test_create_external_account_key_rest_flattened(): + client = PublicCertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PublicCertificateAuthorityServiceRestInterceptor(), + transport="rest", ) - client = PublicCertificateAuthorityServiceClient(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.PublicCertificateAuthorityServiceRestInterceptor, - "post_create_external_account_key", - ) as post, mock.patch.object( - transports.PublicCertificateAuthorityServiceRestInterceptor, - "pre_create_external_account_key", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateExternalAccountKeyRequest.pb( - service.CreateExternalAccountKeyRequest() - ) - 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 = resources.ExternalAccountKey.to_json( - resources.ExternalAccountKey() - ) + # 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 = resources.ExternalAccountKey() - request = service.CreateExternalAccountKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ExternalAccountKey() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - client.create_external_account_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + external_account_key=resources.ExternalAccountKey(name="name_value"), ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ExternalAccountKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_create_external_account_key_rest_bad_request( - transport: str = "rest", request_type=service.CreateExternalAccountKeyRequest -): - client = PublicCertificateAuthorityServiceClient( - 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.create_external_account_key(request) - - -def test_create_external_account_key_rest_flattened(): - client = PublicCertificateAuthorityServiceClient( - 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 = resources.ExternalAccountKey() - - # 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", - external_account_key=resources.ExternalAccountKey(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ExternalAccountKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_external_account_key(**mock_args) + client.create_external_account_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2026,12 +1798,6 @@ def test_create_external_account_key_rest_flattened_error(transport: str = "rest ) -def test_create_external_account_key_rest_error(): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PublicCertificateAuthorityServiceGrpcTransport( @@ -2124,20 +1890,325 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = PublicCertificateAuthorityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_external_account_key_empty_call_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + call.return_value = resources.ExternalAccountKey() + client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PublicCertificateAuthorityServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PublicCertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_external_account_key_empty_call_grpc_asyncio(): + client = PublicCertificateAuthorityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ExternalAccountKey( + name="name_value", + key_id="key_id_value", + b64_mac_key=b"b64_mac_key_blob", + ) + ) + await client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PublicCertificateAuthorityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_external_account_key_rest_bad_request( + request_type=service.CreateExternalAccountKeyRequest, +): + client = PublicCertificateAuthorityServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_external_account_key(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + service.CreateExternalAccountKeyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PublicCertificateAuthorityServiceClient.get_transport_class( - transport_name - )( +def test_create_external_account_key_rest_call_success(request_type): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["external_account_key"] = { + "name": "name_value", + "key_id": "key_id_value", + "b64_mac_key": b"b64_mac_key_blob", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateExternalAccountKeyRequest.meta.fields[ + "external_account_key" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "external_account_key" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["external_account_key"][field])): + del request_init["external_account_key"][field][i][subfield] + else: + del request_init["external_account_key"][field][subfield] + 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 = resources.ExternalAccountKey( + name="name_value", + key_id="key_id_value", + b64_mac_key=b"b64_mac_key_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ExternalAccountKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_external_account_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ExternalAccountKey) + assert response.name == "name_value" + assert response.key_id == "key_id_value" + assert response.b64_mac_key == b"b64_mac_key_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_external_account_key_rest_interceptors(null_interceptor): + transport = transports.PublicCertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PublicCertificateAuthorityServiceRestInterceptor(), + ) + client = PublicCertificateAuthorityServiceClient(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.PublicCertificateAuthorityServiceRestInterceptor, + "post_create_external_account_key", + ) as post, mock.patch.object( + transports.PublicCertificateAuthorityServiceRestInterceptor, + "pre_create_external_account_key", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateExternalAccountKeyRequest.pb( + service.CreateExternalAccountKeyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.ExternalAccountKey.to_json( + resources.ExternalAccountKey() + ) + req.return_value.content = return_value + + request = service.CreateExternalAccountKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ExternalAccountKey() + + client.create_external_account_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_external_account_key_empty_call_rest(): + client = PublicCertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_external_account_key), "__call__" + ) as call: + client.create_external_account_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateExternalAccountKeyRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2742,36 +2813,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PublicCertificateAuthorityServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PublicCertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PublicCertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/async_client.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/async_client.py index 865d49bbb495..acc50adbcd0a 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/async_client.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/async_client.py @@ -1533,11 +1533,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1590,11 +1586,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1651,11 +1643,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1708,11 +1696,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1762,11 +1746,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1819,11 +1799,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/client.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/client.py index bf2954db3df0..2fb015350746 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/client.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/client.py @@ -1956,11 +1956,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2013,11 +2009,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2074,11 +2066,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2131,11 +2119,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2185,11 +2169,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -2242,11 +2222,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/README.rst b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/README.rst new file mode 100644 index 000000000000..3316f5ed751a --- /dev/null +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RapidMigrationAssessmentTransport` is the ABC for all transports. +- public child `RapidMigrationAssessmentGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RapidMigrationAssessmentGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRapidMigrationAssessmentRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RapidMigrationAssessmentRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/base.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/base.py index b26a736de659..952b18c13803 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/base.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/base.py @@ -213,6 +213,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/grpc_asyncio.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/grpc_asyncio.py index 32e69e076296..b83001d64298 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/grpc_asyncio.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -556,17 +560,17 @@ def pause_collector( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_collector: gapic_v1.method_async.wrap_method( + self.create_collector: self._wrap_method( self.create_collector, default_timeout=60.0, client_info=client_info, ), - self.create_annotation: gapic_v1.method_async.wrap_method( + self.create_annotation: self._wrap_method( self.create_annotation, default_timeout=60.0, client_info=client_info, ), - self.get_annotation: gapic_v1.method_async.wrap_method( + self.get_annotation: self._wrap_method( self.get_annotation, default_retry=retries.AsyncRetry( initial=1.0, @@ -581,7 +585,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.list_collectors: gapic_v1.method_async.wrap_method( + self.list_collectors: self._wrap_method( self.list_collectors, default_retry=retries.AsyncRetry( initial=1.0, @@ -596,7 +600,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_collector: gapic_v1.method_async.wrap_method( + self.get_collector: self._wrap_method( self.get_collector, default_retry=retries.AsyncRetry( initial=1.0, @@ -611,36 +615,75 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.update_collector: gapic_v1.method_async.wrap_method( + self.update_collector: self._wrap_method( self.update_collector, default_timeout=60.0, client_info=client_info, ), - self.delete_collector: gapic_v1.method_async.wrap_method( + self.delete_collector: self._wrap_method( self.delete_collector, default_timeout=60.0, client_info=client_info, ), - self.resume_collector: gapic_v1.method_async.wrap_method( + self.resume_collector: self._wrap_method( self.resume_collector, default_timeout=60.0, client_info=client_info, ), - self.register_collector: gapic_v1.method_async.wrap_method( + self.register_collector: self._wrap_method( self.register_collector, default_timeout=60.0, client_info=client_info, ), - self.pause_collector: gapic_v1.method_async.wrap_method( + self.pause_collector: self._wrap_method( self.pause_collector, default_timeout=60.0, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest.py index 8a4b29a8d761..e6faa92302ec 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.rapidmigrationassessment_v1.types import ( api_entities, rapidmigrationassessment, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import RapidMigrationAssessmentTransport +from .rest_base import _BaseRapidMigrationAssessmentRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -551,8 +541,8 @@ class RapidMigrationAssessmentRestStub: _interceptor: RapidMigrationAssessmentRestInterceptor -class RapidMigrationAssessmentRestTransport(RapidMigrationAssessmentTransport): - """REST backend transport for RapidMigrationAssessment. +class RapidMigrationAssessmentRestTransport(_BaseRapidMigrationAssessmentRestTransport): + """REST backend synchronous transport for RapidMigrationAssessment. Service describing handlers for resources. @@ -561,7 +551,6 @@ class RapidMigrationAssessmentRestTransport(RapidMigrationAssessmentTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -615,21 +604,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -694,19 +674,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateAnnotation(RapidMigrationAssessmentRestStub): + class _CreateAnnotation( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("CreateAnnotation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.CreateAnnotation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -735,47 +731,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/annotations", - "body": "annotation", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation._get_http_options() + ) request, metadata = self._interceptor.pre_create_annotation( request, metadata ) - pb_request = rapidmigrationassessment.CreateAnnotationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._CreateAnnotation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -789,21 +774,35 @@ def __call__( resp = self._interceptor.post_create_annotation(resp) return resp - class _CreateCollector(RapidMigrationAssessmentRestStub): + class _CreateCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("CreateCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "collectorId": "", - } - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.CreateCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -832,47 +831,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/collectors", - "body": "collector", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector._get_http_options() + ) request, metadata = self._interceptor.pre_create_collector( request, metadata ) - pb_request = rapidmigrationassessment.CreateCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._CreateCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -886,19 +874,34 @@ def __call__( resp = self._interceptor.post_create_collector(resp) return resp - class _DeleteCollector(RapidMigrationAssessmentRestStub): + class _DeleteCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseDeleteCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("DeleteCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.DeleteCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -927,40 +930,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/collectors/*}", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseDeleteCollector._get_http_options() + ) request, metadata = self._interceptor.pre_delete_collector( request, metadata ) - pb_request = rapidmigrationassessment.DeleteCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseDeleteCollector._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseDeleteCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + RapidMigrationAssessmentRestTransport._DeleteCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -974,19 +968,34 @@ def __call__( resp = self._interceptor.post_delete_collector(resp) return resp - class _GetAnnotation(RapidMigrationAssessmentRestStub): + class _GetAnnotation( + _BaseRapidMigrationAssessmentRestTransport._BaseGetAnnotation, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("GetAnnotation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.GetAnnotation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1013,38 +1022,29 @@ def __call__( Message describing an Annotation """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/annotations/*}", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseGetAnnotation._get_http_options() + ) request, metadata = self._interceptor.pre_get_annotation(request, metadata) - pb_request = rapidmigrationassessment.GetAnnotationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseGetAnnotation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseGetAnnotation._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + RapidMigrationAssessmentRestTransport._GetAnnotation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1060,19 +1060,34 @@ def __call__( resp = self._interceptor.post_get_annotation(resp) return resp - class _GetCollector(RapidMigrationAssessmentRestStub): + class _GetCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseGetCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("GetCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.GetCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1099,38 +1114,29 @@ def __call__( Message describing Collector object. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/collectors/*}", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseGetCollector._get_http_options() + ) request, metadata = self._interceptor.pre_get_collector(request, metadata) - pb_request = rapidmigrationassessment.GetCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseGetCollector._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseGetCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + RapidMigrationAssessmentRestTransport._GetCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1146,19 +1152,34 @@ def __call__( resp = self._interceptor.post_get_collector(resp) return resp - class _ListCollectors(RapidMigrationAssessmentRestStub): + class _ListCollectors( + _BaseRapidMigrationAssessmentRestTransport._BaseListCollectors, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("ListCollectors") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.ListCollectors") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1187,38 +1208,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/collectors", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseListCollectors._get_http_options() + ) request, metadata = self._interceptor.pre_list_collectors(request, metadata) - pb_request = rapidmigrationassessment.ListCollectorsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseListCollectors._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseListCollectors._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + RapidMigrationAssessmentRestTransport._ListCollectors._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1234,19 +1246,35 @@ def __call__( resp = self._interceptor.post_list_collectors(resp) return resp - class _PauseCollector(RapidMigrationAssessmentRestStub): + class _PauseCollector( + _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("PauseCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.PauseCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1275,45 +1303,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/collectors/*}:pause", - "body": "*", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector._get_http_options() + ) request, metadata = self._interceptor.pre_pause_collector(request, metadata) - pb_request = rapidmigrationassessment.PauseCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._PauseCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1327,19 +1344,35 @@ def __call__( resp = self._interceptor.post_pause_collector(resp) return resp - class _RegisterCollector(RapidMigrationAssessmentRestStub): + class _RegisterCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("RegisterCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.RegisterCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1368,47 +1401,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/collectors/*}:register", - "body": "*", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector._get_http_options() + ) request, metadata = self._interceptor.pre_register_collector( request, metadata ) - pb_request = rapidmigrationassessment.RegisterCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._RegisterCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1422,19 +1444,35 @@ def __call__( resp = self._interceptor.post_register_collector(resp) return resp - class _ResumeCollector(RapidMigrationAssessmentRestStub): + class _ResumeCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("ResumeCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.ResumeCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1463,47 +1501,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/collectors/*}:resume", - "body": "*", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector._get_http_options() + ) request, metadata = self._interceptor.pre_resume_collector( request, metadata ) - pb_request = rapidmigrationassessment.ResumeCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._ResumeCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1517,21 +1544,35 @@ def __call__( resp = self._interceptor.post_resume_collector(resp) return resp - class _UpdateCollector(RapidMigrationAssessmentRestStub): + class _UpdateCollector( + _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector, + RapidMigrationAssessmentRestStub, + ): def __hash__(self): - return hash("UpdateCollector") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("RapidMigrationAssessmentRestTransport.UpdateCollector") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1560,47 +1601,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{collector.name=projects/*/locations/*/collectors/*}", - "body": "collector", - }, - ] + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector._get_http_options() + ) request, metadata = self._interceptor.pre_update_collector( request, metadata ) - pb_request = rapidmigrationassessment.UpdateCollectorRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RapidMigrationAssessmentRestTransport._UpdateCollector._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1719,7 +1749,35 @@ def update_collector( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(RapidMigrationAssessmentRestStub): + class _GetLocation( + _BaseRapidMigrationAssessmentRestTransport._BaseGetLocation, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1743,32 +1801,27 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) # 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), + response = RapidMigrationAssessmentRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1776,8 +1829,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1785,7 +1839,35 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(RapidMigrationAssessmentRestStub): + class _ListLocations( + _BaseRapidMigrationAssessmentRestTransport._BaseListLocations, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1809,32 +1891,29 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + RapidMigrationAssessmentRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1842,8 +1921,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1851,7 +1931,36 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(RapidMigrationAssessmentRestStub): + class _CancelOperation( + _BaseRapidMigrationAssessmentRestTransport._BaseCancelOperation, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1872,37 +1981,36 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseRapidMigrationAssessmentRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), - data=body, + response = ( + RapidMigrationAssessmentRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1916,7 +2024,35 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(RapidMigrationAssessmentRestStub): + class _DeleteOperation( + _BaseRapidMigrationAssessmentRestTransport._BaseDeleteOperation, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1937,34 +2073,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + RapidMigrationAssessmentRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1978,7 +2111,35 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(RapidMigrationAssessmentRestStub): + class _GetOperation( + _BaseRapidMigrationAssessmentRestTransport._BaseGetOperation, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -2002,32 +2163,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + RapidMigrationAssessmentRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2035,8 +2193,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -2044,7 +2203,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(RapidMigrationAssessmentRestStub): + class _ListOperations( + _BaseRapidMigrationAssessmentRestTransport._BaseListOperations, + RapidMigrationAssessmentRestStub, + ): + def __hash__(self): + return hash("RapidMigrationAssessmentRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -2068,32 +2255,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseRapidMigrationAssessmentRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRapidMigrationAssessmentRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseRapidMigrationAssessmentRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + RapidMigrationAssessmentRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2101,8 +2285,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest_base.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest_base.py new file mode 100644 index 000000000000..ffed3f562e10 --- /dev/null +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/services/rapid_migration_assessment/transports/rest_base.py @@ -0,0 +1,786 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.rapidmigrationassessment_v1.types import ( + api_entities, + rapidmigrationassessment, +) + +from .base import DEFAULT_CLIENT_INFO, RapidMigrationAssessmentTransport + + +class _BaseRapidMigrationAssessmentRestTransport(RapidMigrationAssessmentTransport): + """Base REST backend transport for RapidMigrationAssessment. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "rapidmigrationassessment.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'rapidmigrationassessment.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateAnnotation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/annotations", + "body": "annotation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.CreateAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateAnnotation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "collectorId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/collectors", + "body": "collector", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.CreateCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseCreateCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/collectors/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.DeleteCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseDeleteCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAnnotation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/annotations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.GetAnnotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseGetAnnotation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collectors/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.GetCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseGetCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCollectors: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/collectors", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.ListCollectorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseListCollectors._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePauseCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/collectors/*}:pause", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.PauseCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BasePauseCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRegisterCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/collectors/*}:register", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.RegisterCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseRegisterCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseResumeCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/collectors/*}:resume", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.ResumeCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseResumeCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCollector: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{collector.name=projects/*/locations/*/collectors/*}", + "body": "collector", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = rapidmigrationassessment.UpdateCollectorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRapidMigrationAssessmentRestTransport._BaseUpdateCollector._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseRapidMigrationAssessmentRestTransport",) diff --git a/packages/google-cloud-rapidmigrationassessment/setup.py b/packages/google-cloud-rapidmigrationassessment/setup.py index ab9e4549907d..82257a993434 100644 --- a/packages/google-cloud-rapidmigrationassessment/setup.py +++ b/packages/google-cloud-rapidmigrationassessment/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-rapidmigrationassessment/tests/unit/gapic/rapidmigrationassessment_v1/test_rapid_migration_assessment.py b/packages/google-cloud-rapidmigrationassessment/tests/unit/gapic/rapidmigrationassessment_v1/test_rapid_migration_assessment.py index 18703a1720b3..a9c12e077ce6 100644 --- a/packages/google-cloud-rapidmigrationassessment/tests/unit/gapic/rapidmigrationassessment_v1/test_rapid_migration_assessment.py +++ b/packages/google-cloud-rapidmigrationassessment/tests/unit/gapic/rapidmigrationassessment_v1/test_rapid_migration_assessment.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.rapidmigrationassessment_v1.services.rapid_migration_assessment import ( RapidMigrationAssessmentAsyncClient, @@ -68,10 +77,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1244,25 +1267,6 @@ def test_create_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.CreateCollectorRequest() - - def test_create_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1337,27 +1341,6 @@ def test_create_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.CreateCollectorRequest() - - @pytest.mark.asyncio async def test_create_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1366,7 +1349,7 @@ async def test_create_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1411,7 +1394,7 @@ async def test_create_collector_async( request_type=rapidmigrationassessment.CreateCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1474,7 +1457,7 @@ def test_create_collector_field_headers(): @pytest.mark.asyncio async def test_create_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1554,7 +1537,7 @@ def test_create_collector_flattened_error(): @pytest.mark.asyncio async def test_create_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1591,7 +1574,7 @@ async def test_create_collector_flattened_async(): @pytest.mark.asyncio async def test_create_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1640,27 +1623,6 @@ def test_create_annotation(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_annotation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_annotation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.CreateAnnotationRequest() - - def test_create_annotation_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1735,29 +1697,6 @@ def test_create_annotation_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_annotation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_annotation), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_annotation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.CreateAnnotationRequest() - - @pytest.mark.asyncio async def test_create_annotation_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1766,7 +1705,7 @@ async def test_create_annotation_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1811,7 +1750,7 @@ async def test_create_annotation_async( request_type=rapidmigrationassessment.CreateAnnotationRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1878,7 +1817,7 @@ def test_create_annotation_field_headers(): @pytest.mark.asyncio async def test_create_annotation_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1957,7 +1896,7 @@ def test_create_annotation_flattened_error(): @pytest.mark.asyncio async def test_create_annotation_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1992,7 +1931,7 @@ async def test_create_annotation_flattened_async(): @pytest.mark.asyncio async def test_create_annotation_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2043,25 +1982,6 @@ def test_get_annotation(request_type, transport: str = "grpc"): assert response.type_ == api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT -def test_get_annotation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_annotation), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_annotation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.GetAnnotationRequest() - - def test_get_annotation_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2125,30 +2045,6 @@ def test_get_annotation_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_annotation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_annotation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - api_entities.Annotation( - name="name_value", - type_=api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT, - ) - ) - response = await client.get_annotation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.GetAnnotationRequest() - - @pytest.mark.asyncio async def test_get_annotation_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2157,7 +2053,7 @@ async def test_get_annotation_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2197,7 +2093,7 @@ async def test_get_annotation_async( request_type=rapidmigrationassessment.GetAnnotationRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2265,7 +2161,7 @@ def test_get_annotation_field_headers(): @pytest.mark.asyncio async def test_get_annotation_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2335,7 +2231,7 @@ def test_get_annotation_flattened_error(): @pytest.mark.asyncio async def test_get_annotation_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2364,7 +2260,7 @@ async def test_get_annotation_flattened_async(): @pytest.mark.asyncio async def test_get_annotation_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2414,25 +2310,6 @@ def test_list_collectors(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_collectors_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_collectors), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_collectors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.ListCollectorsRequest() - - def test_list_collectors_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2502,30 +2379,6 @@ def test_list_collectors_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_collectors_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_collectors), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - rapidmigrationassessment.ListCollectorsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_collectors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.ListCollectorsRequest() - - @pytest.mark.asyncio async def test_list_collectors_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2534,7 +2387,7 @@ async def test_list_collectors_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2574,7 +2427,7 @@ async def test_list_collectors_async( request_type=rapidmigrationassessment.ListCollectorsRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2642,7 +2495,7 @@ def test_list_collectors_field_headers(): @pytest.mark.asyncio async def test_list_collectors_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2712,7 +2565,7 @@ def test_list_collectors_flattened_error(): @pytest.mark.asyncio async def test_list_collectors_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2741,7 +2594,7 @@ async def test_list_collectors_flattened_async(): @pytest.mark.asyncio async def test_list_collectors_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2851,7 +2704,7 @@ def test_list_collectors_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_collectors_async_pager(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2901,7 +2754,7 @@ async def test_list_collectors_async_pager(): @pytest.mark.asyncio async def test_list_collectors_async_pages(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3001,25 +2854,6 @@ def test_get_collector(request_type, transport: str = "grpc"): assert response.eula_uri == "eula_uri_value" -def test_get_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.GetCollectorRequest() - - def test_get_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3083,38 +2917,6 @@ def test_get_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - api_entities.Collector( - name="name_value", - display_name="display_name_value", - description="description_value", - service_account="service_account_value", - bucket="bucket_value", - expected_asset_count=2137, - state=api_entities.Collector.State.STATE_INITIALIZING, - client_version="client_version_value", - collection_days=1596, - eula_uri="eula_uri_value", - ) - ) - response = await client.get_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.GetCollectorRequest() - - @pytest.mark.asyncio async def test_get_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3123,7 +2925,7 @@ async def test_get_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3163,7 +2965,7 @@ async def test_get_collector_async( request_type=rapidmigrationassessment.GetCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3247,7 +3049,7 @@ def test_get_collector_field_headers(): @pytest.mark.asyncio async def test_get_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3317,7 +3119,7 @@ def test_get_collector_flattened_error(): @pytest.mark.asyncio async def test_get_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3346,7 +3148,7 @@ async def test_get_collector_flattened_async(): @pytest.mark.asyncio async def test_get_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3391,25 +3193,6 @@ def test_update_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.UpdateCollectorRequest() - - def test_update_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3480,27 +3263,6 @@ def test_update_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.UpdateCollectorRequest() - - @pytest.mark.asyncio async def test_update_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3509,7 +3271,7 @@ async def test_update_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3554,7 +3316,7 @@ async def test_update_collector_async( request_type=rapidmigrationassessment.UpdateCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3617,7 +3379,7 @@ def test_update_collector_field_headers(): @pytest.mark.asyncio async def test_update_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3692,7 +3454,7 @@ def test_update_collector_flattened_error(): @pytest.mark.asyncio async def test_update_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3725,7 +3487,7 @@ async def test_update_collector_flattened_async(): @pytest.mark.asyncio async def test_update_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3771,25 +3533,6 @@ def test_delete_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.DeleteCollectorRequest() - - def test_delete_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3862,27 +3605,6 @@ def test_delete_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.DeleteCollectorRequest() - - @pytest.mark.asyncio async def test_delete_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3891,7 +3613,7 @@ async def test_delete_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3936,7 +3658,7 @@ async def test_delete_collector_async( request_type=rapidmigrationassessment.DeleteCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3999,7 +3721,7 @@ def test_delete_collector_field_headers(): @pytest.mark.asyncio async def test_delete_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4069,7 +3791,7 @@ def test_delete_collector_flattened_error(): @pytest.mark.asyncio async def test_delete_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4098,7 +3820,7 @@ async def test_delete_collector_flattened_async(): @pytest.mark.asyncio async def test_delete_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4143,25 +3865,6 @@ def test_resume_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_resume_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.resume_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.ResumeCollectorRequest() - - def test_resume_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4234,27 +3937,6 @@ def test_resume_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_resume_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.resume_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.ResumeCollectorRequest() - - @pytest.mark.asyncio async def test_resume_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4263,7 +3945,7 @@ async def test_resume_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4308,7 +3990,7 @@ async def test_resume_collector_async( request_type=rapidmigrationassessment.ResumeCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4371,7 +4053,7 @@ def test_resume_collector_field_headers(): @pytest.mark.asyncio async def test_resume_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4441,7 +4123,7 @@ def test_resume_collector_flattened_error(): @pytest.mark.asyncio async def test_resume_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4470,7 +4152,7 @@ async def test_resume_collector_flattened_async(): @pytest.mark.asyncio async def test_resume_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4517,27 +4199,6 @@ def test_register_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_register_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.register_collector), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.register_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.RegisterCollectorRequest() - - def test_register_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4614,29 +4275,6 @@ def test_register_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_register_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.register_collector), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.register_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.RegisterCollectorRequest() - - @pytest.mark.asyncio async def test_register_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4645,7 +4283,7 @@ async def test_register_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4690,7 +4328,7 @@ async def test_register_collector_async( request_type=rapidmigrationassessment.RegisterCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4757,7 +4395,7 @@ def test_register_collector_field_headers(): @pytest.mark.asyncio async def test_register_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4831,7 +4469,7 @@ def test_register_collector_flattened_error(): @pytest.mark.asyncio async def test_register_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4862,7 +4500,7 @@ async def test_register_collector_flattened_async(): @pytest.mark.asyncio async def test_register_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4907,25 +4545,6 @@ def test_pause_collector(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_pause_collector_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_collector), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.pause_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.PauseCollectorRequest() - - def test_pause_collector_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4996,27 +4615,6 @@ def test_pause_collector_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_pause_collector_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_collector), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.pause_collector() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == rapidmigrationassessment.PauseCollectorRequest() - - @pytest.mark.asyncio async def test_pause_collector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5025,7 +4623,7 @@ async def test_pause_collector_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5070,7 +4668,7 @@ async def test_pause_collector_async( request_type=rapidmigrationassessment.PauseCollectorRequest, ): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5133,7 +4731,7 @@ def test_pause_collector_field_headers(): @pytest.mark.asyncio async def test_pause_collector_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5203,7 +4801,7 @@ def test_pause_collector_flattened_error(): @pytest.mark.asyncio async def test_pause_collector_flattened_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5232,7 +4830,7 @@ async def test_pause_collector_flattened_async(): @pytest.mark.asyncio async def test_pause_collector_flattened_error_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5244,167 +4842,46 @@ async def test_pause_collector_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.CreateCollectorRequest, - dict, - ], -) -def test_create_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_collector_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["collector"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "display_name": "display_name_value", - "description": "description_value", - "service_account": "service_account_value", - "bucket": "bucket_value", - "expected_asset_count": 2137, - "state": 1, - "client_version": "client_version_value", - "guest_os_scan": {"core_source": "core_source_value"}, - "vsphere_scan": {"core_source": "core_source_value"}, - "collection_days": 1596, - "eula_uri": "eula_uri_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = rapidmigrationassessment.CreateCollectorRequest.meta.fields[ - "collector" - ] + # Ensure method has been cached + assert client._transport.create_collector in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_collector + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_collector(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - subfields_not_in_runtime = [] + client.create_collector(request) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["collector"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["collector"][field])): - del request_init["collector"][field][i][subfield] - else: - del request_init["collector"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_collector_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_collector in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_collector - ] = mock_rpc - - request = {} - client.create_collector(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_collector(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 def test_create_collector_rest_required_fields( @@ -5522,90 +4999,6 @@ def test_create_collector_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_create_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_create_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.CreateCollectorRequest.pb( - rapidmigrationassessment.CreateCollectorRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = rapidmigrationassessment.CreateCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_collector_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.CreateCollectorRequest, -): - client = RapidMigrationAssessmentClient( - 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.create_collector(request) - - def test_create_collector_rest_flattened(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5664,169 +5057,52 @@ def test_create_collector_rest_flattened_error(transport: str = "rest"): ) -def test_create_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_annotation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.CreateAnnotationRequest, - dict, - ], -) -def test_create_annotation_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.create_annotation in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["annotation"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "type_": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_annotation + ] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = rapidmigrationassessment.CreateAnnotationRequest.meta.fields[ - "annotation" - ] + request = {} + client.create_annotation(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.create_annotation(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["annotation"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["annotation"][field])): - del request_init["annotation"][field][i][subfield] - else: - del request_init["annotation"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_annotation(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_annotation_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_annotation in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_annotation - ] = mock_rpc - - request = {} - client.create_annotation(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_annotation(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_annotation_rest_required_fields( - request_type=rapidmigrationassessment.CreateAnnotationRequest, -): - transport_class = transports.RapidMigrationAssessmentRestTransport +def test_create_annotation_rest_required_fields( + request_type=rapidmigrationassessment.CreateAnnotationRequest, +): + transport_class = transports.RapidMigrationAssessmentRestTransport request_init = {} request_init["parent"] = "" @@ -5914,90 +5190,6 @@ def test_create_annotation_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_annotation_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_create_annotation" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_create_annotation" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.CreateAnnotationRequest.pb( - rapidmigrationassessment.CreateAnnotationRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = rapidmigrationassessment.CreateAnnotationRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_annotation( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_annotation_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.CreateAnnotationRequest, -): - client = RapidMigrationAssessmentClient( - 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.create_annotation(request) - - def test_create_annotation_rest_flattened(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6055,54 +5247,6 @@ def test_create_annotation_rest_flattened_error(transport: str = "rest"): ) -def test_create_annotation_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.GetAnnotationRequest, - dict, - ], -) -def test_get_annotation_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/annotations/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 = api_entities.Annotation( - name="name_value", - type_=api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = api_entities.Annotation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_annotation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, api_entities.Annotation) - assert response.name == "name_value" - assert response.type_ == api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT - - def test_get_annotation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6222,108 +5366,27 @@ def test_get_annotation_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_annotation_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( +def test_get_annotation_rest_flattened(): + client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), + transport="rest", ) - client = RapidMigrationAssessmentClient(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.RapidMigrationAssessmentRestInterceptor, "post_get_annotation" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_get_annotation" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.GetAnnotationRequest.pb( - rapidmigrationassessment.GetAnnotationRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = api_entities.Annotation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/annotations/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = api_entities.Annotation.to_json( - api_entities.Annotation() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - request = rapidmigrationassessment.GetAnnotationRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = api_entities.Annotation() - - client.get_annotation( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_annotation_rest_bad_request( - transport: str = "rest", request_type=rapidmigrationassessment.GetAnnotationRequest -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/annotations/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.get_annotation(request) - - -def test_get_annotation_rest_flattened(): - client = RapidMigrationAssessmentClient( - 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 = api_entities.Annotation() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/annotations/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6362,54 +5425,6 @@ def test_get_annotation_rest_flattened_error(transport: str = "rest"): ) -def test_get_annotation_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.ListCollectorsRequest, - dict, - ], -) -def test_list_collectors_rest(request_type): - client = RapidMigrationAssessmentClient( - 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 = rapidmigrationassessment.ListCollectorsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = rapidmigrationassessment.ListCollectorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_collectors(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCollectorsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_collectors_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6550,89 +5565,6 @@ def test_list_collectors_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_collectors_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(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.RapidMigrationAssessmentRestInterceptor, "post_list_collectors" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_list_collectors" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.ListCollectorsRequest.pb( - rapidmigrationassessment.ListCollectorsRequest() - ) - 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 = ( - rapidmigrationassessment.ListCollectorsResponse.to_json( - rapidmigrationassessment.ListCollectorsResponse() - ) - ) - - request = rapidmigrationassessment.ListCollectorsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = rapidmigrationassessment.ListCollectorsResponse() - - client.list_collectors( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_collectors_rest_bad_request( - transport: str = "rest", request_type=rapidmigrationassessment.ListCollectorsRequest -): - client = RapidMigrationAssessmentClient( - 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.list_collectors(request) - - def test_list_collectors_rest_flattened(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6752,64 +5684,6 @@ def test_list_collectors_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.GetCollectorRequest, - dict, - ], -) -def test_get_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = api_entities.Collector( - name="name_value", - display_name="display_name_value", - description="description_value", - service_account="service_account_value", - bucket="bucket_value", - expected_asset_count=2137, - state=api_entities.Collector.State.STATE_INITIALIZING, - client_version="client_version_value", - collection_days=1596, - eula_uri="eula_uri_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = api_entities.Collector.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_collector(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, api_entities.Collector) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.service_account == "service_account_value" - assert response.bucket == "bucket_value" - assert response.expected_asset_count == 2137 - assert response.state == api_entities.Collector.State.STATE_INITIALIZING - assert response.client_version == "client_version_value" - assert response.collection_days == 1596 - assert response.eula_uri == "eula_uri_value" - - def test_get_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6929,91 +5803,10 @@ def test_get_collector_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( +def test_get_collector_rest_flattened(): + client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(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.RapidMigrationAssessmentRestInterceptor, "post_get_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_get_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.GetCollectorRequest.pb( - rapidmigrationassessment.GetCollectorRequest() - ) - 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 = api_entities.Collector.to_json( - api_entities.Collector() - ) - - request = rapidmigrationassessment.GetCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = api_entities.Collector() - - client.get_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_collector_rest_bad_request( - transport: str = "rest", request_type=rapidmigrationassessment.GetCollectorRequest -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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.get_collector(request) - - -def test_get_collector_rest_flattened(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7068,135 +5861,6 @@ def test_get_collector_rest_flattened_error(transport: str = "rest"): ) -def test_get_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.UpdateCollectorRequest, - dict, - ], -) -def test_update_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "collector": {"name": "projects/sample1/locations/sample2/collectors/sample3"} - } - request_init["collector"] = { - "name": "projects/sample1/locations/sample2/collectors/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "display_name": "display_name_value", - "description": "description_value", - "service_account": "service_account_value", - "bucket": "bucket_value", - "expected_asset_count": 2137, - "state": 1, - "client_version": "client_version_value", - "guest_os_scan": {"core_source": "core_source_value"}, - "vsphere_scan": {"core_source": "core_source_value"}, - "collection_days": 1596, - "eula_uri": "eula_uri_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = rapidmigrationassessment.UpdateCollectorRequest.meta.fields[ - "collector" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["collector"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["collector"][field])): - del request_init["collector"][field][i][subfield] - else: - del request_init["collector"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7335,116 +5999,30 @@ def test_update_collector_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( +def test_update_collector_rest_flattened(): + client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), + transport="rest", ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_update_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_update_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.UpdateCollectorRequest.pb( - rapidmigrationassessment.UpdateCollectorRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "collector": { + "name": "projects/sample1/locations/sample2/collectors/sample3" + } } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + collector=api_entities.Collector(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - - request = rapidmigrationassessment.UpdateCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_collector_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.UpdateCollectorRequest, -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "collector": {"name": "projects/sample1/locations/sample2/collectors/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.update_collector(request) - - -def test_update_collector_rest_flattened(): - client = RapidMigrationAssessmentClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "collector": { - "name": "projects/sample1/locations/sample2/collectors/sample3" - } - } - - # get truthy value for each flattened field - mock_args = dict( - collector=api_entities.Collector(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7482,47 +6060,6 @@ def test_update_collector_rest_flattened_error(transport: str = "rest"): ) -def test_update_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.DeleteCollectorRequest, - dict, - ], -) -def test_delete_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7647,90 +6184,6 @@ def test_delete_collector_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_delete_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_delete_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.DeleteCollectorRequest.pb( - rapidmigrationassessment.DeleteCollectorRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = rapidmigrationassessment.DeleteCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_collector_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.DeleteCollectorRequest, -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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.delete_collector(request) - - def test_delete_collector_rest_flattened(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7787,47 +6240,6 @@ def test_delete_collector_rest_flattened_error(transport: str = "rest"): ) -def test_delete_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.ResumeCollectorRequest, - dict, - ], -) -def test_resume_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.resume_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_resume_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7951,100 +6363,16 @@ def test_resume_collector_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_resume_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( +def test_resume_collector_rest_flattened(): + client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), + transport="rest", ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_resume_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_resume_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.ResumeCollectorRequest.pb( - rapidmigrationassessment.ResumeCollectorRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = rapidmigrationassessment.ResumeCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.resume_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_resume_collector_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.ResumeCollectorRequest, -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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.resume_collector(request) - - -def test_resume_collector_rest_flattened(): - client = RapidMigrationAssessmentClient( - 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 = operations_pb2.Operation(name="operations/spam") + # 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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -8092,47 +6420,6 @@ def test_resume_collector_rest_flattened_error(transport: str = "rest"): ) -def test_resume_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.RegisterCollectorRequest, - dict, - ], -) -def test_register_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.register_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_register_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8258,90 +6545,6 @@ def test_register_collector_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_register_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), - ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_register_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_register_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.RegisterCollectorRequest.pb( - rapidmigrationassessment.RegisterCollectorRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = rapidmigrationassessment.RegisterCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.register_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_register_collector_rest_bad_request( - transport: str = "rest", - request_type=rapidmigrationassessment.RegisterCollectorRequest, -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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.register_collector(request) - - def test_register_collector_rest_flattened(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8399,47 +6602,6 @@ def test_register_collector_rest_flattened_error(transport: str = "rest"): ) -def test_register_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - rapidmigrationassessment.PauseCollectorRequest, - dict, - ], -) -def test_pause_collector_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.pause_collector(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_pause_collector_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8561,110 +6723,27 @@ def test_pause_collector_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_pause_collector_rest_interceptors(null_interceptor): - transport = transports.RapidMigrationAssessmentRestTransport( +def test_pause_collector_rest_flattened(): + client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RapidMigrationAssessmentRestInterceptor(), + transport="rest", ) - client = RapidMigrationAssessmentClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "post_pause_collector" - ) as post, mock.patch.object( - transports.RapidMigrationAssessmentRestInterceptor, "pre_pause_collector" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = rapidmigrationassessment.PauseCollectorRequest.pb( - rapidmigrationassessment.PauseCollectorRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/collectors/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - request = rapidmigrationassessment.PauseCollectorRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.pause_collector( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_pause_collector_rest_bad_request( - transport: str = "rest", request_type=rapidmigrationassessment.PauseCollectorRequest -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/collectors/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.pause_collector(request) - - -def test_pause_collector_rest_flattened(): - client = RapidMigrationAssessmentClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/collectors/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -8701,12 +6780,6 @@ def test_pause_collector_rest_flattened_error(transport: str = "rest"): ) -def test_pause_collector_rest_error(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RapidMigrationAssessmentGrpcTransport( @@ -8799,1085 +6872,3236 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = RapidMigrationAssessmentClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = RapidMigrationAssessmentClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.RapidMigrationAssessmentGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_collector_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_collector), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_collector(request=None) -def test_rapid_migration_assessment_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RapidMigrationAssessmentTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateCollectorRequest() + assert args[0] == request_msg -def test_rapid_migration_assessment_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.RapidMigrationAssessmentTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_collector", - "create_annotation", - "get_annotation", - "list_collectors", - "get_collector", - "update_collector", - "delete_collector", - "resume_collector", - "register_collector", - "pause_collector", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_annotation_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_annotation(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateAnnotationRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_rapid_migration_assessment_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.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RapidMigrationAssessmentTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_annotation_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_annotation), "__call__") as call: + call.return_value = api_entities.Annotation() + client.get_annotation(request=None) -def test_rapid_migration_assessment_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RapidMigrationAssessmentTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetAnnotationRequest() + assert args[0] == request_msg -def test_rapid_migration_assessment_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RapidMigrationAssessmentClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_collectors_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.RapidMigrationAssessmentGrpcTransport, - transports.RapidMigrationAssessmentGrpcAsyncIOTransport, - ], -) -def test_rapid_migration_assessment_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_collectors), "__call__") as call: + call.return_value = rapidmigrationassessment.ListCollectorsResponse() + client.list_collectors(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ListCollectorsRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.RapidMigrationAssessmentGrpcTransport, - transports.RapidMigrationAssessmentGrpcAsyncIOTransport, - transports.RapidMigrationAssessmentRestTransport, - ], -) -def test_rapid_migration_assessment_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RapidMigrationAssessmentGrpcTransport, grpc_helpers), - (transports.RapidMigrationAssessmentGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_rapid_migration_assessment_transport_create_channel( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_collector_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - create_channel.assert_called_with( - "rapidmigrationassessment.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="rapidmigrationassessment.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_collector), "__call__") as call: + call.return_value = api_entities.Collector() + client.get_collector(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetCollectorRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.RapidMigrationAssessmentGrpcTransport, - transports.RapidMigrationAssessmentGrpcAsyncIOTransport, - ], -) -def test_rapid_migration_assessment_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() + assert args[0] == request_msg - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_collector_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_collector), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_collector(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.UpdateCollectorRequest() -def test_rapid_migration_assessment_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.RapidMigrationAssessmentRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_rapid_migration_assessment_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_collector_empty_call_grpc(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_collector), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_collector(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.DeleteCollectorRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_rapid_migration_assessment_host_no_port(transport_name): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_collector_empty_call_grpc(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="rapidmigrationassessment.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "rapidmigrationassessment.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://rapidmigrationassessment.googleapis.com" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_collector), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.resume_collector(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_rapid_migration_assessment_host_with_port(transport_name): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ResumeCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_register_collector_empty_call_grpc(): client = RapidMigrationAssessmentClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="rapidmigrationassessment.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "rapidmigrationassessment.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://rapidmigrationassessment.googleapis.com:8000" + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_collector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.register_collector(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_rapid_migration_assessment_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RapidMigrationAssessmentClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RapidMigrationAssessmentClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_collector._session - session2 = client2.transport.create_collector._session - assert session1 != session2 - session1 = client1.transport.create_annotation._session - session2 = client2.transport.create_annotation._session - assert session1 != session2 - session1 = client1.transport.get_annotation._session - session2 = client2.transport.get_annotation._session - assert session1 != session2 - session1 = client1.transport.list_collectors._session - session2 = client2.transport.list_collectors._session - assert session1 != session2 - session1 = client1.transport.get_collector._session - session2 = client2.transport.get_collector._session - assert session1 != session2 - session1 = client1.transport.update_collector._session - session2 = client2.transport.update_collector._session - assert session1 != session2 - session1 = client1.transport.delete_collector._session - session2 = client2.transport.delete_collector._session - assert session1 != session2 - session1 = client1.transport.resume_collector._session - session2 = client2.transport.resume_collector._session - assert session1 != session2 - session1 = client1.transport.register_collector._session - session2 = client2.transport.register_collector._session - assert session1 != session2 - session1 = client1.transport.pause_collector._session - session2 = client2.transport.pause_collector._session - assert session1 != session2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.RegisterCollectorRequest() + assert args[0] == request_msg -def test_rapid_migration_assessment_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) - # Check that channel is used if provided. - transport = transports.RapidMigrationAssessmentGrpcTransport( - host="squid.clam.whelk", - channel=channel, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_collector_empty_call_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_collector), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.pause_collector(request=None) -def test_rapid_migration_assessment_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.PauseCollectorRequest() - # Check that channel is used if provided. - transport = transports.RapidMigrationAssessmentGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + assert args[0] == request_msg -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.RapidMigrationAssessmentGrpcTransport, - transports.RapidMigrationAssessmentGrpcAsyncIOTransport, - ], -) -def test_rapid_migration_assessment_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_transport_kind_grpc_asyncio(): + transport = RapidMigrationAssessmentAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() +def test_initialize_client_w_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.RapidMigrationAssessmentGrpcTransport, - transports.RapidMigrationAssessmentGrpcAsyncIOTransport, - ], -) -def test_rapid_migration_assessment_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_collector(request=None) - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateCollectorRequest() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + assert args[0] == request_msg -def test_rapid_migration_assessment_grpc_lro_client(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_annotation_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_annotation(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateAnnotationRequest() + assert args[0] == request_msg -def test_rapid_migration_assessment_grpc_lro_async_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_annotation_empty_call_grpc_asyncio(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_annotation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + api_entities.Annotation( + name="name_value", + type_=api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT, + ) + ) + await client.get_annotation(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetAnnotationRequest() + assert args[0] == request_msg -def test_annotation_path(): - project = "squid" - location = "clam" - annotation = "whelk" - expected = ( - "projects/{project}/locations/{location}/annotations/{annotation}".format( - project=project, - location=location, - annotation=annotation, - ) - ) - actual = RapidMigrationAssessmentClient.annotation_path( - project, location, annotation + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_collectors_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_collectors), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + rapidmigrationassessment.ListCollectorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_collectors(request=None) -def test_parse_annotation_path(): - expected = { - "project": "octopus", - "location": "oyster", - "annotation": "nudibranch", - } - path = RapidMigrationAssessmentClient.annotation_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ListCollectorsRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_annotation_path(path) - assert expected == actual + assert args[0] == request_msg -def test_collector_path(): - project = "cuttlefish" - location = "mussel" - collector = "winkle" - expected = "projects/{project}/locations/{location}/collectors/{collector}".format( - project=project, - location=location, - collector=collector, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.collector_path(project, location, collector) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + api_entities.Collector( + name="name_value", + display_name="display_name_value", + description="description_value", + service_account="service_account_value", + bucket="bucket_value", + expected_asset_count=2137, + state=api_entities.Collector.State.STATE_INITIALIZING, + client_version="client_version_value", + collection_days=1596, + eula_uri="eula_uri_value", + ) + ) + await client.get_collector(request=None) -def test_parse_collector_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "collector": "abalone", - } - path = RapidMigrationAssessmentClient.collector_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetCollectorRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_collector_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.common_billing_account_path(billing_account) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_collector(request=None) -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RapidMigrationAssessmentClient.common_billing_account_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.UpdateCollectorRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_common_billing_account_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.common_folder_path(folder) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_collector(request=None) -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RapidMigrationAssessmentClient.common_folder_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.DeleteCollectorRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_common_folder_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_resume_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.common_organization_path(organization) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.resume_collector(request=None) -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RapidMigrationAssessmentClient.common_organization_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ResumeCollectorRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_common_organization_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_register_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.common_project_path(project) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_collector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.register_collector(request=None) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RapidMigrationAssessmentClient.common_project_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.RegisterCollectorRequest() - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_common_project_path(path) - assert expected == actual + assert args[0] == request_msg -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_pause_collector_empty_call_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - actual = RapidMigrationAssessmentClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RapidMigrationAssessmentClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RapidMigrationAssessmentClient.parse_common_location_path(path) - assert expected == actual - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.RapidMigrationAssessmentTransport, "_prep_wrapped_messages" - ) as prep: - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_collector), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - prep.assert_called_once_with(client_info) + await client.pause_collector(request=None) - with mock.patch.object( - transports.RapidMigrationAssessmentTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = RapidMigrationAssessmentClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.PauseCollectorRequest() + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + +def test_transport_kind_rest(): + transport = RapidMigrationAssessmentClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + assert transport.kind == "rest" -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest +def test_create_collector_rest_bad_request( + request_type=rapidmigrationassessment.CreateCollectorRequest, ): client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_location(request) + client.create_collector(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.GetLocationRequest, + rapidmigrationassessment.CreateCollectorRequest, dict, ], ) -def test_get_location_rest(request_type): +def test_create_collector_rest_call_success(request_type): client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - request_init = {"name": "projects/sample1/locations/sample2"} + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["collector"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "description": "description_value", + "service_account": "service_account_value", + "bucket": "bucket_value", + "expected_asset_count": 2137, + "state": 1, + "client_version": "client_version_value", + "guest_os_scan": {"core_source": "core_source_value"}, + "vsphere_scan": {"core_source": "core_source_value"}, + "collection_days": 1596, + "eula_uri": "eula_uri_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = rapidmigrationassessment.CreateCollectorRequest.meta.fields[ + "collector" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["collector"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["collector"][field])): + del request_init["collector"][field][i][subfield] + else: + del request_init["collector"][field][subfield] 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 = locations_pb2.Location() + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - - response = client.get_location(request) + response = client.create_collector(request) # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + json_return_value = json_format.MessageToJson(return_value) -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): - client = RapidMigrationAssessmentClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), ) + client = RapidMigrationAssessmentClient(transport=transport) - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - - # 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.list_locations(request) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_create_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_create_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.CreateCollectorRequest.pb( + rapidmigrationassessment.CreateCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.CreateCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_annotation_rest_bad_request( + request_type=rapidmigrationassessment.CreateAnnotationRequest, +): + client = RapidMigrationAssessmentClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_annotation(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.ListLocationsRequest, + rapidmigrationassessment.CreateAnnotationRequest, dict, ], ) -def test_list_locations_rest(request_type): +def test_create_annotation_rest_call_success(request_type): client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - request_init = {"name": "projects/sample1"} + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["annotation"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = rapidmigrationassessment.CreateAnnotationRequest.meta.fields[ + "annotation" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["annotation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["annotation"][field])): + del request_init["annotation"][field][i][subfield] + else: + del request_init["annotation"][field][subfield] 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 = locations_pb2.ListLocationsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - - response = client.list_locations(request) + response = client.create_annotation(request) # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + json_return_value = json_format.MessageToJson(return_value) -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = RapidMigrationAssessmentClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_annotation_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), ) + client = RapidMigrationAssessmentClient(transport=transport) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_create_annotation" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_create_annotation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.CreateAnnotationRequest.pb( + rapidmigrationassessment.CreateAnnotationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.CreateAnnotationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_annotation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_annotation_rest_bad_request( + request_type=rapidmigrationassessment.GetAnnotationRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/annotations/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.cancel_operation(request) + client.get_annotation(request) @pytest.mark.parametrize( "request_type", [ - operations_pb2.CancelOperationRequest, + rapidmigrationassessment.GetAnnotationRequest, dict, ], ) -def test_cancel_operation_rest(request_type): +def test_get_annotation_rest_call_success(request_type): client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/annotations/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 = None + return_value = api_entities.Annotation( + name="name_value", + type_=api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT, + ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "{}" - response_value._content = json_return_value.encode("UTF-8") + # Convert return value to protobuf type + return_value = api_entities.Annotation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - - response = client.cancel_operation(request) + response = client.get_annotation(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, api_entities.Annotation) + assert response.name == "name_value" + assert response.type_ == api_entities.Annotation.Type.TYPE_LEGACY_EXPORT_CONSENT -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_annotation_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(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.RapidMigrationAssessmentRestInterceptor, "post_get_annotation" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_get_annotation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.GetAnnotationRequest.pb( + rapidmigrationassessment.GetAnnotationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = api_entities.Annotation.to_json(api_entities.Annotation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.GetAnnotationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = api_entities.Annotation() + + client.get_annotation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_collectors_rest_bad_request( + request_type=rapidmigrationassessment.ListCollectorsRequest, ): client = RapidMigrationAssessmentClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_collectors(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.ListCollectorsRequest, + dict, + ], +) +def test_list_collectors_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + 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 = rapidmigrationassessment.ListCollectorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = rapidmigrationassessment.ListCollectorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_collectors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCollectorsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_collectors_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), ) + client = RapidMigrationAssessmentClient(transport=transport) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_list_collectors" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_list_collectors" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.ListCollectorsRequest.pb( + rapidmigrationassessment.ListCollectorsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = rapidmigrationassessment.ListCollectorsResponse.to_json( + rapidmigrationassessment.ListCollectorsResponse() + ) + req.return_value.content = return_value + + request = rapidmigrationassessment.ListCollectorsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = rapidmigrationassessment.ListCollectorsResponse() + + client.list_collectors( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_collector_rest_bad_request( + request_type=rapidmigrationassessment.GetCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.delete_operation(request) + client.get_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.GetCollectorRequest, + dict, + ], +) +def test_get_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = api_entities.Collector( + name="name_value", + display_name="display_name_value", + description="description_value", + service_account="service_account_value", + bucket="bucket_value", + expected_asset_count=2137, + state=api_entities.Collector.State.STATE_INITIALIZING, + client_version="client_version_value", + collection_days=1596, + eula_uri="eula_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = api_entities.Collector.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_collector(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, api_entities.Collector) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.service_account == "service_account_value" + assert response.bucket == "bucket_value" + assert response.expected_asset_count == 2137 + assert response.state == api_entities.Collector.State.STATE_INITIALIZING + assert response.client_version == "client_version_value" + assert response.collection_days == 1596 + assert response.eula_uri == "eula_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(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.RapidMigrationAssessmentRestInterceptor, "post_get_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_get_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.GetCollectorRequest.pb( + rapidmigrationassessment.GetCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = api_entities.Collector.to_json(api_entities.Collector()) + req.return_value.content = return_value + + request = rapidmigrationassessment.GetCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = api_entities.Collector() + + client.get_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_collector_rest_bad_request( + request_type=rapidmigrationassessment.UpdateCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "collector": {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.UpdateCollectorRequest, + dict, + ], +) +def test_update_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "collector": {"name": "projects/sample1/locations/sample2/collectors/sample3"} + } + request_init["collector"] = { + "name": "projects/sample1/locations/sample2/collectors/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "display_name": "display_name_value", + "description": "description_value", + "service_account": "service_account_value", + "bucket": "bucket_value", + "expected_asset_count": 2137, + "state": 1, + "client_version": "client_version_value", + "guest_os_scan": {"core_source": "core_source_value"}, + "vsphere_scan": {"core_source": "core_source_value"}, + "collection_days": 1596, + "eula_uri": "eula_uri_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = rapidmigrationassessment.UpdateCollectorRequest.meta.fields[ + "collector" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["collector"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["collector"][field])): + del request_init["collector"][field][i][subfield] + else: + del request_init["collector"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_collector(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_update_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_update_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.UpdateCollectorRequest.pb( + rapidmigrationassessment.UpdateCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.UpdateCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_collector_rest_bad_request( + request_type=rapidmigrationassessment.DeleteCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.DeleteCollectorRequest, + dict, + ], +) +def test_delete_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_collector(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_delete_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_delete_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.DeleteCollectorRequest.pb( + rapidmigrationassessment.DeleteCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.DeleteCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resume_collector_rest_bad_request( + request_type=rapidmigrationassessment.ResumeCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.resume_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.ResumeCollectorRequest, + dict, + ], +) +def test_resume_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.resume_collector(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_resume_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_resume_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.ResumeCollectorRequest.pb( + rapidmigrationassessment.ResumeCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.ResumeCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.resume_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_register_collector_rest_bad_request( + request_type=rapidmigrationassessment.RegisterCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.register_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.RegisterCollectorRequest, + dict, + ], +) +def test_register_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.register_collector(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_register_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_register_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_register_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.RegisterCollectorRequest.pb( + rapidmigrationassessment.RegisterCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.RegisterCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.register_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_pause_collector_rest_bad_request( + request_type=rapidmigrationassessment.PauseCollectorRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.pause_collector(request) + + +@pytest.mark.parametrize( + "request_type", + [ + rapidmigrationassessment.PauseCollectorRequest, + dict, + ], +) +def test_pause_collector_rest_call_success(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/collectors/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.pause_collector(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_collector_rest_interceptors(null_interceptor): + transport = transports.RapidMigrationAssessmentRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RapidMigrationAssessmentRestInterceptor(), + ) + client = RapidMigrationAssessmentClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "post_pause_collector" + ) as post, mock.patch.object( + transports.RapidMigrationAssessmentRestInterceptor, "pre_pause_collector" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = rapidmigrationassessment.PauseCollectorRequest.pb( + rapidmigrationassessment.PauseCollectorRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = rapidmigrationassessment.PauseCollectorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.pause_collector( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_collector), "__call__") as call: + client.create_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_annotation_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_annotation), "__call__" + ) as call: + client.create_annotation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.CreateAnnotationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_annotation_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_annotation), "__call__") as call: + client.get_annotation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetAnnotationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_collectors_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_collectors), "__call__") as call: + client.list_collectors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ListCollectorsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_collector), "__call__") as call: + client.get_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.GetCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_collector), "__call__") as call: + client.update_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.UpdateCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_collector), "__call__") as call: + client.delete_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.DeleteCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_collector), "__call__") as call: + client.resume_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.ResumeCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_register_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_collector), "__call__" + ) as call: + client.register_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.RegisterCollectorRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_collector_empty_call_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_collector), "__call__") as call: + client.pause_collector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = rapidmigrationassessment.PauseCollectorRequest() + + assert args[0] == request_msg + + +def test_rapid_migration_assessment_rest_lro_client(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RapidMigrationAssessmentGrpcTransport, + ) + + +def test_rapid_migration_assessment_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RapidMigrationAssessmentTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_rapid_migration_assessment_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RapidMigrationAssessmentTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_collector", + "create_annotation", + "get_annotation", + "list_collectors", + "get_collector", + "update_collector", + "delete_collector", + "resume_collector", + "register_collector", + "pause_collector", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_rapid_migration_assessment_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.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RapidMigrationAssessmentTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_rapid_migration_assessment_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.rapidmigrationassessment_v1.services.rapid_migration_assessment.transports.RapidMigrationAssessmentTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RapidMigrationAssessmentTransport() + adc.assert_called_once() + + +def test_rapid_migration_assessment_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RapidMigrationAssessmentClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RapidMigrationAssessmentGrpcTransport, + transports.RapidMigrationAssessmentGrpcAsyncIOTransport, + ], +) +def test_rapid_migration_assessment_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RapidMigrationAssessmentGrpcTransport, + transports.RapidMigrationAssessmentGrpcAsyncIOTransport, + transports.RapidMigrationAssessmentRestTransport, + ], +) +def test_rapid_migration_assessment_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RapidMigrationAssessmentGrpcTransport, grpc_helpers), + (transports.RapidMigrationAssessmentGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_rapid_migration_assessment_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "rapidmigrationassessment.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="rapidmigrationassessment.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RapidMigrationAssessmentGrpcTransport, + transports.RapidMigrationAssessmentGrpcAsyncIOTransport, + ], +) +def test_rapid_migration_assessment_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_rapid_migration_assessment_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.RapidMigrationAssessmentRestTransport( + 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_rapid_migration_assessment_host_no_port(transport_name): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="rapidmigrationassessment.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "rapidmigrationassessment.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://rapidmigrationassessment.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_rapid_migration_assessment_host_with_port(transport_name): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="rapidmigrationassessment.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "rapidmigrationassessment.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://rapidmigrationassessment.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_rapid_migration_assessment_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RapidMigrationAssessmentClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RapidMigrationAssessmentClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_collector._session + session2 = client2.transport.create_collector._session + assert session1 != session2 + session1 = client1.transport.create_annotation._session + session2 = client2.transport.create_annotation._session + assert session1 != session2 + session1 = client1.transport.get_annotation._session + session2 = client2.transport.get_annotation._session + assert session1 != session2 + session1 = client1.transport.list_collectors._session + session2 = client2.transport.list_collectors._session + assert session1 != session2 + session1 = client1.transport.get_collector._session + session2 = client2.transport.get_collector._session + assert session1 != session2 + session1 = client1.transport.update_collector._session + session2 = client2.transport.update_collector._session + assert session1 != session2 + session1 = client1.transport.delete_collector._session + session2 = client2.transport.delete_collector._session + assert session1 != session2 + session1 = client1.transport.resume_collector._session + session2 = client2.transport.resume_collector._session + assert session1 != session2 + session1 = client1.transport.register_collector._session + session2 = client2.transport.register_collector._session + assert session1 != session2 + session1 = client1.transport.pause_collector._session + session2 = client2.transport.pause_collector._session + assert session1 != session2 + + +def test_rapid_migration_assessment_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RapidMigrationAssessmentGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_rapid_migration_assessment_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RapidMigrationAssessmentGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.RapidMigrationAssessmentGrpcTransport, + transports.RapidMigrationAssessmentGrpcAsyncIOTransport, + ], +) +def test_rapid_migration_assessment_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.RapidMigrationAssessmentGrpcTransport, + transports.RapidMigrationAssessmentGrpcAsyncIOTransport, + ], +) +def test_rapid_migration_assessment_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_rapid_migration_assessment_grpc_lro_client(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_rapid_migration_assessment_grpc_lro_async_client(): + client = RapidMigrationAssessmentAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_annotation_path(): + project = "squid" + location = "clam" + annotation = "whelk" + expected = ( + "projects/{project}/locations/{location}/annotations/{annotation}".format( + project=project, + location=location, + annotation=annotation, + ) + ) + actual = RapidMigrationAssessmentClient.annotation_path( + project, location, annotation + ) + assert expected == actual + + +def test_parse_annotation_path(): + expected = { + "project": "octopus", + "location": "oyster", + "annotation": "nudibranch", + } + path = RapidMigrationAssessmentClient.annotation_path(**expected) + + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_annotation_path(path) + assert expected == actual + + +def test_collector_path(): + project = "cuttlefish" + location = "mussel" + collector = "winkle" + expected = "projects/{project}/locations/{location}/collectors/{collector}".format( + project=project, + location=location, + collector=collector, + ) + actual = RapidMigrationAssessmentClient.collector_path(project, location, collector) + assert expected == actual + + +def test_parse_collector_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "collector": "abalone", + } + path = RapidMigrationAssessmentClient.collector_path(**expected) + + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_collector_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RapidMigrationAssessmentClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RapidMigrationAssessmentClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RapidMigrationAssessmentClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RapidMigrationAssessmentClient.common_folder_path(**expected) -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_common_folder_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = RapidMigrationAssessmentClient.common_organization_path(organization) + assert expected == actual - # 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_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RapidMigrationAssessmentClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RapidMigrationAssessmentClient.common_project_path(project) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RapidMigrationAssessmentClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_common_project_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = RapidMigrationAssessmentClient.common_location_path(project, location) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RapidMigrationAssessmentClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = RapidMigrationAssessmentClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.list_operations(request) + with mock.patch.object( + transports.RapidMigrationAssessmentTransport, "_prep_wrapped_messages" + ) as prep: + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + with mock.patch.object( + transports.RapidMigrationAssessmentTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RapidMigrationAssessmentClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -9907,7 +10131,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9960,7 +10184,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10005,7 +10229,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -10046,7 +10270,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10099,7 +10323,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10144,7 +10368,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -10185,7 +10409,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10240,7 +10464,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10287,7 +10511,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -10330,7 +10554,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10385,7 +10609,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10432,7 +10656,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -10475,7 +10699,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10530,7 +10754,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10577,7 +10801,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -10620,7 +10844,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10675,7 +10899,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials() + credentials=async_anonymous_credentials() ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10722,7 +10946,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = RapidMigrationAssessmentAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -10738,22 +10962,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = RapidMigrationAssessmentClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RapidMigrationAssessmentAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = RapidMigrationAssessmentClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py index bcb1d2f54b4a..558c8aab67c5 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py index bcb1d2f54b4a..558c8aab67c5 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/README.rst b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/README.rst new file mode 100644 index 000000000000..102392385be4 --- /dev/null +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RecaptchaEnterpriseServiceTransport` is the ABC for all transports. +- public child `RecaptchaEnterpriseServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RecaptchaEnterpriseServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRecaptchaEnterpriseServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RecaptchaEnterpriseServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py index 00886fe8df24..1de0e29e087c 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -841,110 +845,119 @@ def search_related_account_group_memberships( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_assessment: gapic_v1.method_async.wrap_method( + self.create_assessment: self._wrap_method( self.create_assessment, default_timeout=600.0, client_info=client_info, ), - self.annotate_assessment: gapic_v1.method_async.wrap_method( + self.annotate_assessment: self._wrap_method( self.annotate_assessment, default_timeout=600.0, client_info=client_info, ), - self.create_key: gapic_v1.method_async.wrap_method( + self.create_key: self._wrap_method( self.create_key, default_timeout=600.0, client_info=client_info, ), - self.list_keys: gapic_v1.method_async.wrap_method( + self.list_keys: self._wrap_method( self.list_keys, default_timeout=600.0, client_info=client_info, ), - self.retrieve_legacy_secret_key: gapic_v1.method_async.wrap_method( + self.retrieve_legacy_secret_key: self._wrap_method( self.retrieve_legacy_secret_key, default_timeout=None, client_info=client_info, ), - self.get_key: gapic_v1.method_async.wrap_method( + self.get_key: self._wrap_method( self.get_key, default_timeout=600.0, client_info=client_info, ), - self.update_key: gapic_v1.method_async.wrap_method( + self.update_key: self._wrap_method( self.update_key, default_timeout=600.0, client_info=client_info, ), - self.delete_key: gapic_v1.method_async.wrap_method( + self.delete_key: self._wrap_method( self.delete_key, default_timeout=600.0, client_info=client_info, ), - self.migrate_key: gapic_v1.method_async.wrap_method( + self.migrate_key: self._wrap_method( self.migrate_key, default_timeout=None, client_info=client_info, ), - self.add_ip_override: gapic_v1.method_async.wrap_method( + self.add_ip_override: self._wrap_method( self.add_ip_override, default_timeout=None, client_info=client_info, ), - self.get_metrics: gapic_v1.method_async.wrap_method( + self.get_metrics: self._wrap_method( self.get_metrics, default_timeout=None, client_info=client_info, ), - self.create_firewall_policy: gapic_v1.method_async.wrap_method( + self.create_firewall_policy: self._wrap_method( self.create_firewall_policy, default_timeout=None, client_info=client_info, ), - self.list_firewall_policies: gapic_v1.method_async.wrap_method( + self.list_firewall_policies: self._wrap_method( self.list_firewall_policies, default_timeout=None, client_info=client_info, ), - self.get_firewall_policy: gapic_v1.method_async.wrap_method( + self.get_firewall_policy: self._wrap_method( self.get_firewall_policy, default_timeout=None, client_info=client_info, ), - self.update_firewall_policy: gapic_v1.method_async.wrap_method( + self.update_firewall_policy: self._wrap_method( self.update_firewall_policy, default_timeout=None, client_info=client_info, ), - self.delete_firewall_policy: gapic_v1.method_async.wrap_method( + self.delete_firewall_policy: self._wrap_method( self.delete_firewall_policy, default_timeout=None, client_info=client_info, ), - self.reorder_firewall_policies: gapic_v1.method_async.wrap_method( + self.reorder_firewall_policies: self._wrap_method( self.reorder_firewall_policies, default_timeout=None, client_info=client_info, ), - self.list_related_account_groups: gapic_v1.method_async.wrap_method( + self.list_related_account_groups: self._wrap_method( self.list_related_account_groups, default_timeout=None, client_info=client_info, ), - self.list_related_account_group_memberships: gapic_v1.method_async.wrap_method( + self.list_related_account_group_memberships: self._wrap_method( self.list_related_account_group_memberships, default_timeout=None, client_info=client_info, ), - self.search_related_account_group_memberships: gapic_v1.method_async.wrap_method( + self.search_related_account_group_memberships: self._wrap_method( self.search_related_account_group_memberships, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("RecaptchaEnterpriseServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json index 225f39c961dd..b2ad3f987f98 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/snippet_metadata_google.cloud.recaptchaenterprise.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-recaptcha-enterprise", - "version": "1.22.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-recaptcha-enterprise/setup.py b/packages/google-cloud-recaptcha-enterprise/setup.py index 275f2ac078ca..d3fcf89cf9cf 100644 --- a/packages/google-cloud-recaptcha-enterprise/setup.py +++ b/packages/google-cloud-recaptcha-enterprise/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py b/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py index 9230f6fa88c3..cab29893173f 100644 --- a/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py +++ b/packages/google-cloud-recaptcha-enterprise/tests/unit/gapic/recaptchaenterprise_v1/test_recaptcha_enterprise_service.py @@ -24,8 +24,22 @@ import math +from google.api_core import api_core_version +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,11 +50,6 @@ from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -import grpc -from grpc.experimental import aio -from proto.marshal.rules import wrappers -from proto.marshal.rules.dates import DurationRule, TimestampRule -import pytest from google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service import ( RecaptchaEnterpriseServiceAsyncClient, @@ -51,10 +60,24 @@ from google.cloud.recaptchaenterprise_v1.types import recaptchaenterprise +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1193,27 +1216,6 @@ def test_create_assessment(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_create_assessment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_assessment), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_assessment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateAssessmentRequest() - - def test_create_assessment_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1281,31 +1283,6 @@ def test_create_assessment_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_assessment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_assessment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Assessment( - name="name_value", - ) - ) - response = await client.create_assessment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateAssessmentRequest() - - @pytest.mark.asyncio async def test_create_assessment_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1314,7 +1291,7 @@ async def test_create_assessment_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1354,7 +1331,7 @@ async def test_create_assessment_async( request_type=recaptchaenterprise.CreateAssessmentRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1424,7 +1401,7 @@ def test_create_assessment_field_headers(): @pytest.mark.asyncio async def test_create_assessment_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1503,7 +1480,7 @@ def test_create_assessment_flattened_error(): @pytest.mark.asyncio async def test_create_assessment_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1538,7 +1515,7 @@ async def test_create_assessment_flattened_async(): @pytest.mark.asyncio async def test_create_assessment_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1586,27 +1563,6 @@ def test_annotate_assessment(request_type, transport: str = "grpc"): assert isinstance(response, recaptchaenterprise.AnnotateAssessmentResponse) -def test_annotate_assessment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_assessment), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.annotate_assessment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.AnnotateAssessmentRequest() - - def test_annotate_assessment_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1678,29 +1634,6 @@ def test_annotate_assessment_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_annotate_assessment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.annotate_assessment), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.AnnotateAssessmentResponse() - ) - response = await client.annotate_assessment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.AnnotateAssessmentRequest() - - @pytest.mark.asyncio async def test_annotate_assessment_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1709,7 +1642,7 @@ async def test_annotate_assessment_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1749,7 +1682,7 @@ async def test_annotate_assessment_async( request_type=recaptchaenterprise.AnnotateAssessmentRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1816,7 +1749,7 @@ def test_annotate_assessment_field_headers(): @pytest.mark.asyncio async def test_annotate_assessment_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1895,7 +1828,7 @@ def test_annotate_assessment_flattened_error(): @pytest.mark.asyncio async def test_annotate_assessment_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1930,7 +1863,7 @@ async def test_annotate_assessment_flattened_async(): @pytest.mark.asyncio async def test_annotate_assessment_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1981,25 +1914,6 @@ def test_create_key(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_create_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateKeyRequest() - - def test_create_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2063,37 +1977,13 @@ def test_create_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Key( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.create_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateKeyRequest() - - @pytest.mark.asyncio async def test_create_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2132,7 +2022,7 @@ async def test_create_key_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.CreateKeyRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2200,7 +2090,7 @@ def test_create_key_field_headers(): @pytest.mark.asyncio async def test_create_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2275,7 +2165,7 @@ def test_create_key_flattened_error(): @pytest.mark.asyncio async def test_create_key_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2308,7 +2198,7 @@ async def test_create_key_flattened_async(): @pytest.mark.asyncio async def test_create_key_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2357,25 +2247,6 @@ def test_list_keys(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_keys_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_keys), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListKeysRequest() - - def test_list_keys_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2441,36 +2312,13 @@ def test_list_keys_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_keys_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_keys), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.ListKeysResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListKeysRequest() - - @pytest.mark.asyncio async def test_list_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2509,7 +2357,7 @@ async def test_list_keys_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.ListKeysRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2575,7 +2423,7 @@ def test_list_keys_field_headers(): @pytest.mark.asyncio async def test_list_keys_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2645,7 +2493,7 @@ def test_list_keys_flattened_error(): @pytest.mark.asyncio async def test_list_keys_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2674,7 +2522,7 @@ async def test_list_keys_flattened_async(): @pytest.mark.asyncio async def test_list_keys_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2784,7 +2632,7 @@ def test_list_keys_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_keys_async_pager(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2834,7 +2682,7 @@ async def test_list_keys_async_pager(): @pytest.mark.asyncio async def test_list_keys_async_pages(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2918,27 +2766,6 @@ def test_retrieve_legacy_secret_key(request_type, transport: str = "grpc"): assert response.legacy_secret_key == "legacy_secret_key_value" -def test_retrieve_legacy_secret_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_legacy_secret_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.retrieve_legacy_secret_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.RetrieveLegacySecretKeyRequest() - - def test_retrieve_legacy_secret_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3009,31 +2836,6 @@ def test_retrieve_legacy_secret_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_retrieve_legacy_secret_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_legacy_secret_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.RetrieveLegacySecretKeyResponse( - legacy_secret_key="legacy_secret_key_value", - ) - ) - response = await client.retrieve_legacy_secret_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.RetrieveLegacySecretKeyRequest() - - @pytest.mark.asyncio async def test_retrieve_legacy_secret_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3042,7 +2844,7 @@ async def test_retrieve_legacy_secret_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3082,7 +2884,7 @@ async def test_retrieve_legacy_secret_key_async( request_type=recaptchaenterprise.RetrieveLegacySecretKeyRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3152,7 +2954,7 @@ def test_retrieve_legacy_secret_key_field_headers(): @pytest.mark.asyncio async def test_retrieve_legacy_secret_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3226,7 +3028,7 @@ def test_retrieve_legacy_secret_key_flattened_error(): @pytest.mark.asyncio async def test_retrieve_legacy_secret_key_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3257,7 +3059,7 @@ async def test_retrieve_legacy_secret_key_flattened_async(): @pytest.mark.asyncio async def test_retrieve_legacy_secret_key_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3307,25 +3109,6 @@ def test_get_key(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_get_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetKeyRequest() - - def test_get_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3389,37 +3172,13 @@ def test_get_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Key( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.get_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetKeyRequest() - - @pytest.mark.asyncio async def test_get_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3458,7 +3217,7 @@ async def test_get_key_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.GetKeyRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3526,7 +3285,7 @@ def test_get_key_field_headers(): @pytest.mark.asyncio async def test_get_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3596,7 +3355,7 @@ def test_get_key_flattened_error(): @pytest.mark.asyncio async def test_get_key_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3625,7 +3384,7 @@ async def test_get_key_flattened_async(): @pytest.mark.asyncio async def test_get_key_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3675,25 +3434,6 @@ def test_update_key(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.UpdateKeyRequest() - - def test_update_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3753,37 +3493,13 @@ def test_update_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Key( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.update_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.UpdateKeyRequest() - - @pytest.mark.asyncio async def test_update_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3822,7 +3538,7 @@ async def test_update_key_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.UpdateKeyRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3890,7 +3606,7 @@ def test_update_key_field_headers(): @pytest.mark.asyncio async def test_update_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3965,7 +3681,7 @@ def test_update_key_flattened_error(): @pytest.mark.asyncio async def test_update_key_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3998,7 +3714,7 @@ async def test_update_key_flattened_async(): @pytest.mark.asyncio async def test_update_key_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4044,25 +3760,6 @@ def test_delete_key(request_type, transport: str = "grpc"): assert response is None -def test_delete_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.DeleteKeyRequest() - - def test_delete_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4126,32 +3823,13 @@ def test_delete_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.DeleteKeyRequest() - - @pytest.mark.asyncio async def test_delete_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4190,7 +3868,7 @@ async def test_delete_key_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.DeleteKeyRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4251,7 +3929,7 @@ def test_delete_key_field_headers(): @pytest.mark.asyncio async def test_delete_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4319,7 +3997,7 @@ def test_delete_key_flattened_error(): @pytest.mark.asyncio async def test_delete_key_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4346,7 +4024,7 @@ async def test_delete_key_flattened_async(): @pytest.mark.asyncio async def test_delete_key_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4396,25 +4074,6 @@ def test_migrate_key(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_migrate_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.migrate_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.migrate_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.MigrateKeyRequest() - - def test_migrate_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4478,30 +4137,6 @@ def test_migrate_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_migrate_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.migrate_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Key( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.migrate_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.MigrateKeyRequest() - - @pytest.mark.asyncio async def test_migrate_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4510,7 +4145,7 @@ async def test_migrate_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4549,7 +4184,7 @@ async def test_migrate_key_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.MigrateKeyRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4617,7 +4252,7 @@ def test_migrate_key_field_headers(): @pytest.mark.asyncio async def test_migrate_key_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4679,25 +4314,6 @@ def test_add_ip_override(request_type, transport: str = "grpc"): assert isinstance(response, recaptchaenterprise.AddIpOverrideResponse) -def test_add_ip_override_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_ip_override), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_ip_override() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.AddIpOverrideRequest() - - def test_add_ip_override_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4761,27 +4377,6 @@ def test_add_ip_override_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_ip_override_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_ip_override), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.AddIpOverrideResponse() - ) - response = await client.add_ip_override() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.AddIpOverrideRequest() - - @pytest.mark.asyncio async def test_add_ip_override_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4790,7 +4385,7 @@ async def test_add_ip_override_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4830,7 +4425,7 @@ async def test_add_ip_override_async( request_type=recaptchaenterprise.AddIpOverrideRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4893,7 +4488,7 @@ def test_add_ip_override_field_headers(): @pytest.mark.asyncio async def test_add_ip_override_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4968,7 +4563,7 @@ def test_add_ip_override_flattened_error(): @pytest.mark.asyncio async def test_add_ip_override_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5001,7 +4596,7 @@ async def test_add_ip_override_flattened_async(): @pytest.mark.asyncio async def test_add_ip_override_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5050,25 +4645,6 @@ def test_get_metrics(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_metrics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_metrics), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetMetricsRequest() - - def test_get_metrics_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5132,29 +4708,6 @@ def test_get_metrics_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_metrics_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_metrics), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.Metrics( - name="name_value", - ) - ) - response = await client.get_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetMetricsRequest() - - @pytest.mark.asyncio async def test_get_metrics_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5163,7 +4716,7 @@ async def test_get_metrics_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5202,7 +4755,7 @@ async def test_get_metrics_async( transport: str = "grpc_asyncio", request_type=recaptchaenterprise.GetMetricsRequest ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5268,7 +4821,7 @@ def test_get_metrics_field_headers(): @pytest.mark.asyncio async def test_get_metrics_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5338,7 +4891,7 @@ def test_get_metrics_flattened_error(): @pytest.mark.asyncio async def test_get_metrics_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5367,7 +4920,7 @@ async def test_get_metrics_flattened_async(): @pytest.mark.asyncio async def test_get_metrics_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5423,27 +4976,6 @@ def test_create_firewall_policy(request_type, transport: str = "grpc"): assert response.condition == "condition_value" -def test_create_firewall_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateFirewallPolicyRequest() - - def test_create_firewall_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5514,34 +5046,6 @@ def test_create_firewall_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_firewall_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.FirewallPolicy( - name="name_value", - description="description_value", - path="path_value", - condition="condition_value", - ) - ) - response = await client.create_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.CreateFirewallPolicyRequest() - - @pytest.mark.asyncio async def test_create_firewall_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5550,7 +5054,7 @@ async def test_create_firewall_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5590,7 +5094,7 @@ async def test_create_firewall_policy_async( request_type=recaptchaenterprise.CreateFirewallPolicyRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5666,7 +5170,7 @@ def test_create_firewall_policy_field_headers(): @pytest.mark.asyncio async def test_create_firewall_policy_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5745,7 +5249,7 @@ def test_create_firewall_policy_flattened_error(): @pytest.mark.asyncio async def test_create_firewall_policy_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5780,7 +5284,7 @@ async def test_create_firewall_policy_flattened_async(): @pytest.mark.asyncio async def test_create_firewall_policy_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5831,27 +5335,6 @@ def test_list_firewall_policies(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_firewall_policies_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_policies), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_firewall_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListFirewallPoliciesRequest() - - def test_list_firewall_policies_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5925,41 +5408,16 @@ def test_list_firewall_policies_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_firewall_policies_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_policies), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.ListFirewallPoliciesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_firewall_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListFirewallPoliciesRequest() - - -@pytest.mark.asyncio -async def test_list_firewall_policies_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_list_firewall_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -5997,7 +5455,7 @@ async def test_list_firewall_policies_async( request_type=recaptchaenterprise.ListFirewallPoliciesRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6067,7 +5525,7 @@ def test_list_firewall_policies_field_headers(): @pytest.mark.asyncio async def test_list_firewall_policies_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6141,7 +5599,7 @@ def test_list_firewall_policies_flattened_error(): @pytest.mark.asyncio async def test_list_firewall_policies_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6172,7 +5630,7 @@ async def test_list_firewall_policies_flattened_async(): @pytest.mark.asyncio async def test_list_firewall_policies_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6286,7 +5744,7 @@ def test_list_firewall_policies_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_firewall_policies_async_pager(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6338,7 +5796,7 @@ async def test_list_firewall_policies_async_pager(): @pytest.mark.asyncio async def test_list_firewall_policies_async_pages(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6430,27 +5888,6 @@ def test_get_firewall_policy(request_type, transport: str = "grpc"): assert response.condition == "condition_value" -def test_get_firewall_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetFirewallPolicyRequest() - - def test_get_firewall_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6520,34 +5957,6 @@ def test_get_firewall_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_firewall_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.FirewallPolicy( - name="name_value", - description="description_value", - path="path_value", - condition="condition_value", - ) - ) - response = await client.get_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.GetFirewallPolicyRequest() - - @pytest.mark.asyncio async def test_get_firewall_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6556,7 +5965,7 @@ async def test_get_firewall_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6596,7 +6005,7 @@ async def test_get_firewall_policy_async( request_type=recaptchaenterprise.GetFirewallPolicyRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6672,7 +6081,7 @@ def test_get_firewall_policy_field_headers(): @pytest.mark.asyncio async def test_get_firewall_policy_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6746,7 +6155,7 @@ def test_get_firewall_policy_flattened_error(): @pytest.mark.asyncio async def test_get_firewall_policy_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6777,7 +6186,7 @@ async def test_get_firewall_policy_flattened_async(): @pytest.mark.asyncio async def test_get_firewall_policy_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6833,27 +6242,6 @@ def test_update_firewall_policy(request_type, transport: str = "grpc"): assert response.condition == "condition_value" -def test_update_firewall_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.UpdateFirewallPolicyRequest() - - def test_update_firewall_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6920,34 +6308,6 @@ def test_update_firewall_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_firewall_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.FirewallPolicy( - name="name_value", - description="description_value", - path="path_value", - condition="condition_value", - ) - ) - response = await client.update_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.UpdateFirewallPolicyRequest() - - @pytest.mark.asyncio async def test_update_firewall_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6956,7 +6316,7 @@ async def test_update_firewall_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6996,7 +6356,7 @@ async def test_update_firewall_policy_async( request_type=recaptchaenterprise.UpdateFirewallPolicyRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7072,7 +6432,7 @@ def test_update_firewall_policy_field_headers(): @pytest.mark.asyncio async def test_update_firewall_policy_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7151,7 +6511,7 @@ def test_update_firewall_policy_flattened_error(): @pytest.mark.asyncio async def test_update_firewall_policy_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7186,7 +6546,7 @@ async def test_update_firewall_policy_flattened_async(): @pytest.mark.asyncio async def test_update_firewall_policy_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7234,27 +6594,6 @@ def test_delete_firewall_policy(request_type, transport: str = "grpc"): assert response is None -def test_delete_firewall_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_policy), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.DeleteFirewallPolicyRequest() - - def test_delete_firewall_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7325,27 +6664,6 @@ def test_delete_firewall_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_firewall_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_firewall_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.DeleteFirewallPolicyRequest() - - @pytest.mark.asyncio async def test_delete_firewall_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7354,7 +6672,7 @@ async def test_delete_firewall_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7394,7 +6712,7 @@ async def test_delete_firewall_policy_async( request_type=recaptchaenterprise.DeleteFirewallPolicyRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7459,7 +6777,7 @@ def test_delete_firewall_policy_field_headers(): @pytest.mark.asyncio async def test_delete_firewall_policy_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7531,7 +6849,7 @@ def test_delete_firewall_policy_flattened_error(): @pytest.mark.asyncio async def test_delete_firewall_policy_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7560,7 +6878,7 @@ async def test_delete_firewall_policy_flattened_async(): @pytest.mark.asyncio async def test_delete_firewall_policy_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -7607,27 +6925,6 @@ def test_reorder_firewall_policies(request_type, transport: str = "grpc"): assert isinstance(response, recaptchaenterprise.ReorderFirewallPoliciesResponse) -def test_reorder_firewall_policies_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reorder_firewall_policies), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.reorder_firewall_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ReorderFirewallPoliciesRequest() - - def test_reorder_firewall_policies_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7698,29 +6995,6 @@ def test_reorder_firewall_policies_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_reorder_firewall_policies_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reorder_firewall_policies), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.ReorderFirewallPoliciesResponse() - ) - response = await client.reorder_firewall_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ReorderFirewallPoliciesRequest() - - @pytest.mark.asyncio async def test_reorder_firewall_policies_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7729,7 +7003,7 @@ async def test_reorder_firewall_policies_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7769,7 +7043,7 @@ async def test_reorder_firewall_policies_async( request_type=recaptchaenterprise.ReorderFirewallPoliciesRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7836,7 +7110,7 @@ def test_reorder_firewall_policies_field_headers(): @pytest.mark.asyncio async def test_reorder_firewall_policies_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7915,7 +7189,7 @@ def test_reorder_firewall_policies_flattened_error(): @pytest.mark.asyncio async def test_reorder_firewall_policies_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7950,7 +7224,7 @@ async def test_reorder_firewall_policies_flattened_async(): @pytest.mark.asyncio async def test_reorder_firewall_policies_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8001,27 +7275,6 @@ def test_list_related_account_groups(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_related_account_groups_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_related_account_groups), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_related_account_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListRelatedAccountGroupsRequest() - - def test_list_related_account_groups_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8094,31 +7347,6 @@ def test_list_related_account_groups_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_related_account_groups_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_related_account_groups), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.ListRelatedAccountGroupsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_related_account_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recaptchaenterprise.ListRelatedAccountGroupsRequest() - - @pytest.mark.asyncio async def test_list_related_account_groups_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8127,7 +7355,7 @@ async def test_list_related_account_groups_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8167,7 +7395,7 @@ async def test_list_related_account_groups_async( request_type=recaptchaenterprise.ListRelatedAccountGroupsRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8237,7 +7465,7 @@ def test_list_related_account_groups_field_headers(): @pytest.mark.asyncio async def test_list_related_account_groups_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8311,7 +7539,7 @@ def test_list_related_account_groups_flattened_error(): @pytest.mark.asyncio async def test_list_related_account_groups_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8342,7 +7570,7 @@ async def test_list_related_account_groups_flattened_async(): @pytest.mark.asyncio async def test_list_related_account_groups_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -8460,7 +7688,7 @@ def test_list_related_account_groups_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_related_account_groups_async_pager(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8514,7 +7742,7 @@ async def test_list_related_account_groups_async_pager(): @pytest.mark.asyncio async def test_list_related_account_groups_async_pages(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8602,29 +7830,6 @@ def test_list_related_account_group_memberships(request_type, transport: str = " assert response.next_page_token == "next_page_token_value" -def test_list_related_account_group_memberships_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_related_account_group_memberships), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_related_account_group_memberships() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] == recaptchaenterprise.ListRelatedAccountGroupMembershipsRequest() - ) - - def test_list_related_account_group_memberships_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -8697,33 +7902,6 @@ def test_list_related_account_group_memberships_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_related_account_group_memberships_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_related_account_group_memberships), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.ListRelatedAccountGroupMembershipsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_related_account_group_memberships() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] == recaptchaenterprise.ListRelatedAccountGroupMembershipsRequest() - ) - - @pytest.mark.asyncio async def test_list_related_account_group_memberships_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -8732,7 +7910,7 @@ async def test_list_related_account_group_memberships_async_use_cached_wrapped_r # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8772,7 +7950,7 @@ async def test_list_related_account_group_memberships_async( request_type=recaptchaenterprise.ListRelatedAccountGroupMembershipsRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8844,7 +8022,7 @@ def test_list_related_account_group_memberships_field_headers(): @pytest.mark.asyncio async def test_list_related_account_group_memberships_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8920,7 +8098,7 @@ def test_list_related_account_group_memberships_flattened_error(): @pytest.mark.asyncio async def test_list_related_account_group_memberships_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -8953,7 +8131,7 @@ async def test_list_related_account_group_memberships_flattened_async(): @pytest.mark.asyncio async def test_list_related_account_group_memberships_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9072,7 +8250,7 @@ def test_list_related_account_group_memberships_pages(transport_name: str = "grp @pytest.mark.asyncio async def test_list_related_account_group_memberships_async_pager(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9127,7 +8305,7 @@ async def test_list_related_account_group_memberships_async_pager(): @pytest.mark.asyncio async def test_list_related_account_group_memberships_async_pages(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9217,29 +8395,6 @@ def test_search_related_account_group_memberships( assert response.next_page_token == "next_page_token_value" -def test_search_related_account_group_memberships_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_related_account_group_memberships), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_related_account_group_memberships() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] == recaptchaenterprise.SearchRelatedAccountGroupMembershipsRequest() - ) - - def test_search_related_account_group_memberships_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -9316,33 +8471,6 @@ def test_search_related_account_group_memberships_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_related_account_group_memberships_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_related_account_group_memberships), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recaptchaenterprise.SearchRelatedAccountGroupMembershipsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_related_account_group_memberships() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] == recaptchaenterprise.SearchRelatedAccountGroupMembershipsRequest() - ) - - @pytest.mark.asyncio async def test_search_related_account_group_memberships_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -9351,7 +8479,7 @@ async def test_search_related_account_group_memberships_async_use_cached_wrapped # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9391,7 +8519,7 @@ async def test_search_related_account_group_memberships_async( request_type=recaptchaenterprise.SearchRelatedAccountGroupMembershipsRequest, ): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9463,7 +8591,7 @@ def test_search_related_account_group_memberships_field_headers(): @pytest.mark.asyncio async def test_search_related_account_group_memberships_field_headers_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9544,7 +8672,7 @@ def test_search_related_account_group_memberships_flattened_error(): @pytest.mark.asyncio async def test_search_related_account_group_memberships_flattened_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9581,7 +8709,7 @@ async def test_search_related_account_group_memberships_flattened_async(): @pytest.mark.asyncio async def test_search_related_account_group_memberships_flattened_error_async(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -9701,7 +8829,7 @@ def test_search_related_account_group_memberships_pages(transport_name: str = "g @pytest.mark.asyncio async def test_search_related_account_group_memberships_async_pager(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9756,7 +8884,7 @@ async def test_search_related_account_group_memberships_async_pager(): @pytest.mark.asyncio async def test_search_related_account_group_memberships_async_pages(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -9895,151 +9023,1177 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = RecaptchaEnterpriseServiceClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = RecaptchaEnterpriseServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_assessment_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.kind == transport_name + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_assessment), "__call__" + ) as call: + call.return_value = recaptchaenterprise.Assessment() + client.create_assessment(request=None) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateAssessmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_annotate_assessment_empty_call_grpc(): client = RecaptchaEnterpriseServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert isinstance( - client.transport, - transports.RecaptchaEnterpriseServiceGrpcTransport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + call.return_value = recaptchaenterprise.AnnotateAssessmentResponse() + client.annotate_assessment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.AnnotateAssessmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + client.create_key(request=None) -def test_recaptcha_enterprise_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RecaptchaEnterpriseServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateKeyRequest() + assert args[0] == request_msg -def test_recaptcha_enterprise_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.RecaptchaEnterpriseServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_assessment", - "annotate_assessment", - "create_key", - "list_keys", - "retrieve_legacy_secret_key", - "get_key", - "update_key", - "delete_key", - "migrate_key", - "add_ip_override", - "get_metrics", - "create_firewall_policy", - "list_firewall_policies", - "get_firewall_policy", - "update_firewall_policy", - "delete_firewall_policy", - "reorder_firewall_policies", - "list_related_account_groups", - "list_related_account_group_memberships", - "search_related_account_group_memberships", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_keys_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: + call.return_value = recaptchaenterprise.ListKeysResponse() + client.list_keys(request=None) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListKeysRequest() + assert args[0] == request_msg -def test_recaptcha_enterprise_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_legacy_secret_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecaptchaEnterpriseServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + type(client.transport.retrieve_legacy_secret_key), "__call__" + ) as call: + call.return_value = recaptchaenterprise.RetrieveLegacySecretKeyResponse() + client.retrieve_legacy_secret_key(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.RetrieveLegacySecretKeyRequest() -def test_recaptcha_enterprise_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecaptchaEnterpriseServiceTransport() - adc.assert_called_once() + assert args[0] == request_msg -def test_recaptcha_enterprise_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RecaptchaEnterpriseServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + client.get_key(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.RecaptchaEnterpriseServiceGrpcTransport, - transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, - ], -) -def test_recaptcha_enterprise_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + client.update_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.UpdateKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: + call.return_value = None + client.delete_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.DeleteKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_migrate_key_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.migrate_key), "__call__") as call: + call.return_value = recaptchaenterprise.Key() + client.migrate_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.MigrateKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_ip_override_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_ip_override), "__call__") as call: + call.return_value = recaptchaenterprise.AddIpOverrideResponse() + client.add_ip_override(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.AddIpOverrideRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_metrics_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_metrics), "__call__") as call: + call.return_value = recaptchaenterprise.Metrics() + client.get_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetMetricsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_firewall_policy_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_policy), "__call__" + ) as call: + call.return_value = recaptchaenterprise.FirewallPolicy() + client.create_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_firewall_policies_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_policies), "__call__" + ) as call: + call.return_value = recaptchaenterprise.ListFirewallPoliciesResponse() + client.list_firewall_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListFirewallPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_firewall_policy_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_policy), "__call__" + ) as call: + call.return_value = recaptchaenterprise.FirewallPolicy() + client.get_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_firewall_policy_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_policy), "__call__" + ) as call: + call.return_value = recaptchaenterprise.FirewallPolicy() + client.update_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.UpdateFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_firewall_policy_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_policy), "__call__" + ) as call: + call.return_value = None + client.delete_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.DeleteFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reorder_firewall_policies_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reorder_firewall_policies), "__call__" + ) as call: + call.return_value = recaptchaenterprise.ReorderFirewallPoliciesResponse() + client.reorder_firewall_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ReorderFirewallPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_related_account_groups_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_related_account_groups), "__call__" + ) as call: + call.return_value = recaptchaenterprise.ListRelatedAccountGroupsResponse() + client.list_related_account_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListRelatedAccountGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_related_account_group_memberships_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_related_account_group_memberships), "__call__" + ) as call: + call.return_value = ( + recaptchaenterprise.ListRelatedAccountGroupMembershipsResponse() + ) + client.list_related_account_group_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListRelatedAccountGroupMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_related_account_group_memberships_empty_call_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_related_account_group_memberships), "__call__" + ) as call: + call.return_value = ( + recaptchaenterprise.SearchRelatedAccountGroupMembershipsResponse() + ) + client.search_related_account_group_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.SearchRelatedAccountGroupMembershipsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RecaptchaEnterpriseServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_assessment_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_assessment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Assessment( + name="name_value", + ) + ) + await client.create_assessment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateAssessmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_annotate_assessment_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.annotate_assessment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.AnnotateAssessmentResponse() + ) + await client.annotate_assessment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.AnnotateAssessmentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + ) + ) + await client.create_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_keys_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_keys), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListKeysResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_legacy_secret_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_legacy_secret_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.RetrieveLegacySecretKeyResponse( + legacy_secret_key="legacy_secret_key_value", + ) + ) + await client.retrieve_legacy_secret_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.RetrieveLegacySecretKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + ) + ) + await client.get_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + ) + ) + await client.update_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.UpdateKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.DeleteKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_migrate_key_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.migrate_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Key( + name="name_value", + display_name="display_name_value", + ) + ) + await client.migrate_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.MigrateKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_ip_override_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_ip_override), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.AddIpOverrideResponse() + ) + await client.add_ip_override(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.AddIpOverrideRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_metrics_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_metrics), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.Metrics( + name="name_value", + ) + ) + await client.get_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetMetricsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_firewall_policy_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.FirewallPolicy( + name="name_value", + description="description_value", + path="path_value", + condition="condition_value", + ) + ) + await client.create_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.CreateFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_firewall_policies_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListFirewallPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_firewall_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListFirewallPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_firewall_policy_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.FirewallPolicy( + name="name_value", + description="description_value", + path="path_value", + condition="condition_value", + ) + ) + await client.get_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.GetFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_firewall_policy_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.FirewallPolicy( + name="name_value", + description="description_value", + path="path_value", + condition="condition_value", + ) + ) + await client.update_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.UpdateFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_firewall_policy_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_firewall_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.DeleteFirewallPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_reorder_firewall_policies_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reorder_firewall_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ReorderFirewallPoliciesResponse() + ) + await client.reorder_firewall_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ReorderFirewallPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_related_account_groups_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_related_account_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListRelatedAccountGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_related_account_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListRelatedAccountGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_related_account_group_memberships_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_related_account_group_memberships), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.ListRelatedAccountGroupMembershipsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_related_account_group_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.ListRelatedAccountGroupMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_related_account_group_memberships_empty_call_grpc_asyncio(): + client = RecaptchaEnterpriseServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_related_account_group_memberships), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recaptchaenterprise.SearchRelatedAccountGroupMembershipsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_related_account_group_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recaptchaenterprise.SearchRelatedAccountGroupMembershipsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RecaptchaEnterpriseServiceGrpcTransport, + ) + + +def test_recaptcha_enterprise_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_recaptcha_enterprise_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_assessment", + "annotate_assessment", + "create_key", + "list_keys", + "retrieve_legacy_secret_key", + "get_key", + "update_key", + "delete_key", + "migrate_key", + "add_ip_override", + "get_metrics", + "create_firewall_policy", + "list_firewall_policies", + "get_firewall_policy", + "update_firewall_policy", + "delete_firewall_policy", + "reorder_firewall_policies", + "list_related_account_groups", + "list_related_account_group_memberships", + "search_related_account_group_memberships", + ) + 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_recaptcha_enterprise_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.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecaptchaEnterpriseServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_recaptcha_enterprise_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.recaptchaenterprise_v1.services.recaptcha_enterprise_service.transports.RecaptchaEnterpriseServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecaptchaEnterpriseServiceTransport() + adc.assert_called_once() + + +def test_recaptcha_enterprise_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RecaptchaEnterpriseServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RecaptchaEnterpriseServiceGrpcTransport, + transports.RecaptchaEnterpriseServiceGrpcAsyncIOTransport, + ], +) +def test_recaptcha_enterprise_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) @pytest.mark.parametrize( @@ -10591,37 +10745,31 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = RecaptchaEnterpriseServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = RecaptchaEnterpriseServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RecaptchaEnterpriseServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() - - def test_client_ctx(): transports = [ "grpc", diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/README.rst b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/README.rst new file mode 100644 index 000000000000..c14dcbeef235 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CatalogServiceTransport` is the ABC for all transports. +- public child `CatalogServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CatalogServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCatalogServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CatalogServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py index 54e71ddac132..851088c51b64 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -441,7 +445,7 @@ def import_catalog_items( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_catalog_item: gapic_v1.method_async.wrap_method( + self.create_catalog_item: self._wrap_method( self.create_catalog_item, default_retry=retries.AsyncRetry( initial=0.1, @@ -456,7 +460,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.get_catalog_item: gapic_v1.method_async.wrap_method( + self.get_catalog_item: self._wrap_method( self.get_catalog_item, default_retry=retries.AsyncRetry( initial=0.1, @@ -471,7 +475,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.list_catalog_items: gapic_v1.method_async.wrap_method( + self.list_catalog_items: self._wrap_method( self.list_catalog_items, default_retry=retries.AsyncRetry( initial=0.1, @@ -486,7 +490,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.update_catalog_item: gapic_v1.method_async.wrap_method( + self.update_catalog_item: self._wrap_method( self.update_catalog_item, default_retry=retries.AsyncRetry( initial=0.1, @@ -501,7 +505,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.delete_catalog_item: gapic_v1.method_async.wrap_method( + self.delete_catalog_item: self._wrap_method( self.delete_catalog_item, default_retry=retries.AsyncRetry( initial=0.1, @@ -516,7 +520,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.import_catalog_items: gapic_v1.method_async.wrap_method( + self.import_catalog_items: self._wrap_method( self.import_catalog_items, default_retry=retries.AsyncRetry( initial=0.1, @@ -533,8 +537,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("CatalogServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py index 4856ea81d74f..80bc4415064b 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py @@ -16,34 +16,18 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.recommendationengine_v1beta1.types import ( catalog, @@ -51,8 +35,14 @@ import_, ) -from .base import CatalogServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCatalogServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -261,8 +251,8 @@ class CatalogServiceRestStub: _interceptor: CatalogServiceRestInterceptor -class CatalogServiceRestTransport(CatalogServiceTransport): - """REST backend transport for CatalogService. +class CatalogServiceRestTransport(_BaseCatalogServiceRestTransport): + """REST backend synchronous transport for CatalogService. Service for ingesting catalog information of the customer's website. @@ -272,7 +262,6 @@ class CatalogServiceRestTransport(CatalogServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -326,21 +315,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -400,19 +380,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateCatalogItem(CatalogServiceRestStub): + class _CreateCatalogItem( + _BaseCatalogServiceRestTransport._BaseCreateCatalogItem, CatalogServiceRestStub + ): def __hash__(self): - return hash("CreateCatalogItem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.CreateCatalogItem") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -441,47 +436,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems", - "body": "catalog_item", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseCreateCatalogItem._get_http_options() + ) request, metadata = self._interceptor.pre_create_catalog_item( request, metadata ) - pb_request = catalog_service.CreateCatalogItemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseCreateCatalogItem._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseCreateCatalogItem._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseCreateCatalogItem._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._CreateCatalogItem._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -497,19 +479,33 @@ def __call__( resp = self._interceptor.post_create_catalog_item(resp) return resp - class _DeleteCatalogItem(CatalogServiceRestStub): + class _DeleteCatalogItem( + _BaseCatalogServiceRestTransport._BaseDeleteCatalogItem, CatalogServiceRestStub + ): def __hash__(self): - return hash("DeleteCatalogItem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.DeleteCatalogItem") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -532,40 +528,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseDeleteCatalogItem._get_http_options() + ) request, metadata = self._interceptor.pre_delete_catalog_item( request, metadata ) - pb_request = catalog_service.DeleteCatalogItemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseDeleteCatalogItem._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseDeleteCatalogItem._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._DeleteCatalogItem._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -573,19 +558,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetCatalogItem(CatalogServiceRestStub): + class _GetCatalogItem( + _BaseCatalogServiceRestTransport._BaseGetCatalogItem, CatalogServiceRestStub + ): def __hash__(self): - return hash("GetCatalogItem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetCatalogItem") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -614,40 +613,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetCatalogItem._get_http_options() + ) request, metadata = self._interceptor.pre_get_catalog_item( request, metadata ) - pb_request = catalog_service.GetCatalogItemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetCatalogItem._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetCatalogItem._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetCatalogItem._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -663,19 +651,34 @@ def __call__( resp = self._interceptor.post_get_catalog_item(resp) return resp - class _ImportCatalogItems(CatalogServiceRestStub): + class _ImportCatalogItems( + _BaseCatalogServiceRestTransport._BaseImportCatalogItems, CatalogServiceRestStub + ): def __hash__(self): - return hash("ImportCatalogItems") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ImportCatalogItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -704,47 +707,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseImportCatalogItems._get_http_options() + ) request, metadata = self._interceptor.pre_import_catalog_items( request, metadata ) - pb_request = import_.ImportCatalogItemsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseImportCatalogItems._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseImportCatalogItems._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseImportCatalogItems._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._ImportCatalogItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -758,19 +748,33 @@ def __call__( resp = self._interceptor.post_import_catalog_items(resp) return resp - class _ListCatalogItems(CatalogServiceRestStub): + class _ListCatalogItems( + _BaseCatalogServiceRestTransport._BaseListCatalogItems, CatalogServiceRestStub + ): def __hash__(self): - return hash("ListCatalogItems") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ListCatalogItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -799,40 +803,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseListCatalogItems._get_http_options() + ) request, metadata = self._interceptor.pre_list_catalog_items( request, metadata ) - pb_request = catalog_service.ListCatalogItemsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListCatalogItems._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseListCatalogItems._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._ListCatalogItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -848,19 +841,34 @@ def __call__( resp = self._interceptor.post_list_catalog_items(resp) return resp - class _UpdateCatalogItem(CatalogServiceRestStub): + class _UpdateCatalogItem( + _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem, CatalogServiceRestStub + ): def __hash__(self): - return hash("UpdateCatalogItem") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCatalogItem") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -889,47 +897,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", - "body": "catalog_item", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem._get_http_options() + ) request, metadata = self._interceptor.pre_update_catalog_item( request, metadata ) - pb_request = catalog_service.UpdateCatalogItemRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._UpdateCatalogItem._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest_base.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest_base.py new file mode 100644 index 000000000000..aedef79aae41 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest_base.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.recommendationengine_v1beta1.types import ( + catalog, + catalog_service, + import_, +) + +from .base import DEFAULT_CLIENT_INFO, CatalogServiceTransport + + +class _BaseCatalogServiceRestTransport(CatalogServiceTransport): + """Base REST backend transport for CatalogService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommendationengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommendationengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateCatalogItem: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems", + "body": "catalog_item", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.CreateCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseCreateCatalogItem._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCatalogItem: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.DeleteCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseDeleteCatalogItem._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCatalogItem: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetCatalogItem._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportCatalogItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_.ImportCatalogItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseImportCatalogItems._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCatalogItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ListCatalogItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseListCatalogItems._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCatalogItem: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}", + "body": "catalog_item", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCatalogItem._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseCatalogServiceRestTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/README.rst b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/README.rst new file mode 100644 index 000000000000..28f1d7273165 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PredictionApiKeyRegistryTransport` is the ABC for all transports. +- public child `PredictionApiKeyRegistryGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PredictionApiKeyRegistryGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePredictionApiKeyRegistryRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PredictionApiKeyRegistryRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py index 5b0ea660ec92..d1c124c847f3 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -348,7 +352,7 @@ def delete_prediction_api_key_registration( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_prediction_api_key_registration: gapic_v1.method_async.wrap_method( + self.create_prediction_api_key_registration: self._wrap_method( self.create_prediction_api_key_registration, default_retry=retries.AsyncRetry( initial=0.1, @@ -363,7 +367,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.list_prediction_api_key_registrations: gapic_v1.method_async.wrap_method( + self.list_prediction_api_key_registrations: self._wrap_method( self.list_prediction_api_key_registrations, default_retry=retries.AsyncRetry( initial=0.1, @@ -378,7 +382,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.delete_prediction_api_key_registration: gapic_v1.method_async.wrap_method( + self.delete_prediction_api_key_registration: self._wrap_method( self.delete_prediction_api_key_registration, default_retry=retries.AsyncRetry( initial=0.1, @@ -395,8 +399,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PredictionApiKeyRegistryGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py index 0f593f88d866..d7cfa474cdae 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 empty_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.protobuf import empty_pb2 # type: ignore - from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PredictionApiKeyRegistryTransport +from .rest_base import _BasePredictionApiKeyRegistryRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -169,8 +165,8 @@ class PredictionApiKeyRegistryRestStub: _interceptor: PredictionApiKeyRegistryRestInterceptor -class PredictionApiKeyRegistryRestTransport(PredictionApiKeyRegistryTransport): - """REST backend transport for PredictionApiKeyRegistry. +class PredictionApiKeyRegistryRestTransport(_BasePredictionApiKeyRegistryRestTransport): + """REST backend synchronous transport for PredictionApiKeyRegistry. Service for registering API keys for use with the ``predict`` method. If you use an API key to request predictions, you must first @@ -184,7 +180,6 @@ class PredictionApiKeyRegistryRestTransport(PredictionApiKeyRegistryTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -238,21 +233,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -263,19 +249,37 @@ def __init__( self._interceptor = interceptor or PredictionApiKeyRegistryRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreatePredictionApiKeyRegistration(PredictionApiKeyRegistryRestStub): + class _CreatePredictionApiKeyRegistration( + _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration, + PredictionApiKeyRegistryRestStub, + ): def __hash__(self): - return hash("CreatePredictionApiKeyRegistration") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "PredictionApiKeyRegistryRestTransport.CreatePredictionApiKeyRegistration" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -303,52 +307,37 @@ def __call__( Registered Api Key. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations", - "body": "*", - }, - ] + http_options = ( + _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_create_prediction_api_key_registration( request, metadata ) - pb_request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb( - request + transcoded_request = _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PredictionApiKeyRegistryRestTransport._CreatePredictionApiKeyRegistration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -366,19 +355,36 @@ def __call__( resp = self._interceptor.post_create_prediction_api_key_registration(resp) return resp - class _DeletePredictionApiKeyRegistration(PredictionApiKeyRegistryRestStub): + class _DeletePredictionApiKeyRegistration( + _BasePredictionApiKeyRegistryRestTransport._BaseDeletePredictionApiKeyRegistration, + PredictionApiKeyRegistryRestStub, + ): def __hash__(self): - return hash("DeletePredictionApiKeyRegistration") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "PredictionApiKeyRegistryRestTransport.DeletePredictionApiKeyRegistration" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -402,45 +408,32 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}", - }, - ] + http_options = ( + _BasePredictionApiKeyRegistryRestTransport._BaseDeletePredictionApiKeyRegistration._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_delete_prediction_api_key_registration( request, metadata ) - pb_request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb( - request + transcoded_request = _BasePredictionApiKeyRegistryRestTransport._BaseDeletePredictionApiKeyRegistration._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BasePredictionApiKeyRegistryRestTransport._BaseDeletePredictionApiKeyRegistration._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PredictionApiKeyRegistryRestTransport._DeletePredictionApiKeyRegistration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -448,19 +441,36 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _ListPredictionApiKeyRegistrations(PredictionApiKeyRegistryRestStub): + class _ListPredictionApiKeyRegistrations( + _BasePredictionApiKeyRegistryRestTransport._BaseListPredictionApiKeyRegistrations, + PredictionApiKeyRegistryRestStub, + ): def __hash__(self): - return hash("ListPredictionApiKeyRegistrations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "PredictionApiKeyRegistryRestTransport.ListPredictionApiKeyRegistrations" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -492,45 +502,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations", - }, - ] + http_options = ( + _BasePredictionApiKeyRegistryRestTransport._BaseListPredictionApiKeyRegistrations._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_list_prediction_api_key_registrations( request, metadata ) - pb_request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb( - request + transcoded_request = _BasePredictionApiKeyRegistryRestTransport._BaseListPredictionApiKeyRegistrations._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BasePredictionApiKeyRegistryRestTransport._BaseListPredictionApiKeyRegistrations._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = PredictionApiKeyRegistryRestTransport._ListPredictionApiKeyRegistrations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest_base.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest_base.py new file mode 100644 index 000000000000..5f1dd96ae3a3 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest_base.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.recommendationengine_v1beta1.types import ( + prediction_apikey_registry_service, +) + +from .base import DEFAULT_CLIENT_INFO, PredictionApiKeyRegistryTransport + + +class _BasePredictionApiKeyRegistryRestTransport(PredictionApiKeyRegistryTransport): + """Base REST backend transport for PredictionApiKeyRegistry. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommendationengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommendationengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreatePredictionApiKeyRegistration: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionApiKeyRegistryRestTransport._BaseCreatePredictionApiKeyRegistration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePredictionApiKeyRegistration: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionApiKeyRegistryRestTransport._BaseDeletePredictionApiKeyRegistration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPredictionApiKeyRegistrations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionApiKeyRegistryRestTransport._BaseListPredictionApiKeyRegistrations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePredictionApiKeyRegistryRestTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/README.rst b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/README.rst new file mode 100644 index 000000000000..504aaca0a144 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PredictionServiceTransport` is the ABC for all transports. +- public child `PredictionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PredictionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePredictionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PredictionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py index b68aa273bc15..cf292e2009f3 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -226,6 +227,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -274,7 +278,7 @@ def predict( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.predict: gapic_v1.method_async.wrap_method( + self.predict: self._wrap_method( self.predict, default_retry=retries.AsyncRetry( initial=0.1, @@ -291,8 +295,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("PredictionServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py index 1339c732a456..9a623dcf53cd 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.recommendationengine_v1beta1.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePredictionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.recommendationengine_v1beta1.types import prediction_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PredictionServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -108,8 +105,8 @@ class PredictionServiceRestStub: _interceptor: PredictionServiceRestInterceptor -class PredictionServiceRestTransport(PredictionServiceTransport): - """REST backend transport for PredictionService. +class PredictionServiceRestTransport(_BasePredictionServiceRestTransport): + """REST backend synchronous transport for PredictionService. Service for making recommendation prediction. @@ -118,7 +115,6 @@ class PredictionServiceRestTransport(PredictionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -172,21 +168,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -197,19 +184,34 @@ def __init__( self._interceptor = interceptor or PredictionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Predict(PredictionServiceRestStub): + class _Predict( + _BasePredictionServiceRestTransport._BasePredict, PredictionServiceRestStub + ): def __hash__(self): - return hash("Predict") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PredictionServiceRestTransport.Predict") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -235,45 +237,36 @@ def __call__( Response message for predict method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/placements/*}:predict", - "body": "*", - }, - ] + http_options = ( + _BasePredictionServiceRestTransport._BasePredict._get_http_options() + ) request, metadata = self._interceptor.pre_predict(request, metadata) - pb_request = prediction_service.PredictRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePredictionServiceRestTransport._BasePredict._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BasePredictionServiceRestTransport._BasePredict._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BasePredictionServiceRestTransport._BasePredict._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PredictionServiceRestTransport._Predict._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest_base.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest_base.py new file mode 100644 index 000000000000..cfcf3bfc5763 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest_base.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.recommendationengine_v1beta1.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO, PredictionServiceTransport + + +class _BasePredictionServiceRestTransport(PredictionServiceTransport): + """Base REST backend transport for PredictionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommendationengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommendationengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BasePredict: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/placements/*}:predict", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_service.PredictRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionServiceRestTransport._BasePredict._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BasePredictionServiceRestTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/README.rst b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/README.rst new file mode 100644 index 000000000000..45f0ef746528 --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserEventServiceTransport` is the ABC for all transports. +- public child `UserEventServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserEventServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserEventServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserEventServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py index 332b8941b3a5..c0277db65ecd 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -422,7 +426,7 @@ def import_user_events( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.write_user_event: gapic_v1.method_async.wrap_method( + self.write_user_event: self._wrap_method( self.write_user_event, default_retry=retries.AsyncRetry( initial=0.1, @@ -437,7 +441,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.collect_user_event: gapic_v1.method_async.wrap_method( + self.collect_user_event: self._wrap_method( self.collect_user_event, default_retry=retries.AsyncRetry( initial=0.1, @@ -452,7 +456,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.list_user_events: gapic_v1.method_async.wrap_method( + self.list_user_events: self._wrap_method( self.list_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -467,7 +471,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.purge_user_events: gapic_v1.method_async.wrap_method( + self.purge_user_events: self._wrap_method( self.purge_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -482,7 +486,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.import_user_events: gapic_v1.method_async.wrap_method( + self.import_user_events: self._wrap_method( self.import_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -499,8 +503,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("UserEventServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py index 4fe66f514c03..739cda19f572 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event from google.cloud.recommendationengine_v1beta1.types import import_ from google.cloud.recommendationengine_v1beta1.types import user_event_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import UserEventServiceTransport +from .rest_base import _BaseUserEventServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -243,8 +233,8 @@ class UserEventServiceRestStub: _interceptor: UserEventServiceRestInterceptor -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. +class UserEventServiceRestTransport(_BaseUserEventServiceRestTransport): + """REST backend synchronous transport for UserEventService. Service for ingesting end user actions on the customer website. @@ -254,7 +244,6 @@ class UserEventServiceRestTransport(UserEventServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -308,21 +297,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -382,21 +362,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CollectUserEvent(UserEventServiceRestStub): + class _CollectUserEvent( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent": "", - } - - @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 - } + return hash("UserEventServiceRestTransport.CollectUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -472,40 +465,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:collect", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_collect_user_event( request, metadata ) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = UserEventServiceRestTransport._CollectUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -521,19 +503,35 @@ def __call__( resp = self._interceptor.post_collect_user_event(resp) return resp - class _ImportUserEvents(UserEventServiceRestStub): + class _ImportUserEvents( + _BaseUserEventServiceRestTransport._BaseImportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ImportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -563,47 +561,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_import_user_events( request, metadata ) - pb_request = import_.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ImportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -617,19 +602,33 @@ def __call__( resp = self._interceptor.post_import_user_events(resp) return resp - class _ListUserEvents(UserEventServiceRestStub): + class _ListUserEvents( + _BaseUserEventServiceRestTransport._BaseListUserEvents, UserEventServiceRestStub + ): def __hash__(self): - return hash("ListUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ListUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -658,40 +657,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseListUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_list_user_events( request, metadata ) - pb_request = user_event_service.ListUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseListUserEvents._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseListUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = UserEventServiceRestTransport._ListUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -707,19 +695,35 @@ def __call__( resp = self._interceptor.post_list_user_events(resp) return resp - class _PurgeUserEvents(UserEventServiceRestStub): + class _PurgeUserEvents( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("PurgeUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.PurgeUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -749,47 +753,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:purge", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_purge_user_events( request, metadata ) - pb_request = user_event_service.PurgeUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._PurgeUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -803,19 +794,34 @@ def __call__( resp = self._interceptor.post_purge_user_events(resp) return resp - class _WriteUserEvent(UserEventServiceRestStub): + class _WriteUserEvent( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent, UserEventServiceRestStub + ): def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.WriteUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -846,47 +852,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:write", - "body": "user_event", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_write_user_event( request, metadata ) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._WriteUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest_base.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest_base.py new file mode 100644 index 000000000000..51e7af45ea0e --- /dev/null +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest_base.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event_service + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + + +class _BaseUserEventServiceRestTransport(UserEventServiceTransport): + """Base REST backend transport for UserEventService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommendationengine.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommendationengine.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCollectUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:collect", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.ListUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseListUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseWriteUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:write", + "body": "user_event", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseUserEventServiceRestTransport",) diff --git a/packages/google-cloud-recommendations-ai/setup.py b/packages/google-cloud-recommendations-ai/setup.py index f0fae4359451..6f10e106d140 100644 --- a/packages/google-cloud-recommendations-ai/setup.py +++ b/packages/google-cloud-recommendations-ai/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py index e8019247639b..6d9220b20422 100644 --- a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py +++ b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,15 +62,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceAsyncClient, @@ -70,10 +79,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1183,27 +1206,6 @@ def test_create_catalog_item(request_type, transport: str = "grpc"): assert response.item_group_id == "item_group_id_value" -def test_create_catalog_item_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.CreateCatalogItemRequest() - - def test_create_catalog_item_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1273,36 +1275,6 @@ def test_create_catalog_item_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_catalog_item_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_catalog_item), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - ) - response = await client.create_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.CreateCatalogItemRequest() - - @pytest.mark.asyncio async def test_create_catalog_item_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1311,7 +1283,7 @@ async def test_create_catalog_item_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1351,7 +1323,7 @@ async def test_create_catalog_item_async( request_type=catalog_service.CreateCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1431,7 +1403,7 @@ def test_create_catalog_item_field_headers(): @pytest.mark.asyncio async def test_create_catalog_item_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1508,7 +1480,7 @@ def test_create_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_create_catalog_item_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1541,7 +1513,7 @@ async def test_create_catalog_item_flattened_async(): @pytest.mark.asyncio async def test_create_catalog_item_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1600,25 +1572,6 @@ def test_get_catalog_item(request_type, transport: str = "grpc"): assert response.item_group_id == "item_group_id_value" -def test_get_catalog_item_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_catalog_item), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCatalogItemRequest() - - def test_get_catalog_item_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1684,34 +1637,6 @@ def test_get_catalog_item_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_catalog_item_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_catalog_item), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - ) - response = await client.get_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCatalogItemRequest() - - @pytest.mark.asyncio async def test_get_catalog_item_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1720,7 +1645,7 @@ async def test_get_catalog_item_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1759,7 +1684,7 @@ async def test_get_catalog_item_async( transport: str = "grpc_asyncio", request_type=catalog_service.GetCatalogItemRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1835,7 +1760,7 @@ def test_get_catalog_item_field_headers(): @pytest.mark.asyncio async def test_get_catalog_item_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1903,7 +1828,7 @@ def test_get_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_get_catalog_item_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1930,7 +1855,7 @@ async def test_get_catalog_item_flattened_async(): @pytest.mark.asyncio async def test_get_catalog_item_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1980,27 +1905,6 @@ def test_list_catalog_items(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_catalog_items_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogItemsRequest() - - def test_list_catalog_items_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2074,31 +1978,6 @@ def test_list_catalog_items_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_catalog_items_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_catalog_items), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.ListCatalogItemsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogItemsRequest() - - @pytest.mark.asyncio async def test_list_catalog_items_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2107,7 +1986,7 @@ async def test_list_catalog_items_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2147,7 +2026,7 @@ async def test_list_catalog_items_async( request_type=catalog_service.ListCatalogItemsRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2217,7 +2096,7 @@ def test_list_catalog_items_field_headers(): @pytest.mark.asyncio async def test_list_catalog_items_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2296,7 +2175,7 @@ def test_list_catalog_items_flattened_error(): @pytest.mark.asyncio async def test_list_catalog_items_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2331,7 +2210,7 @@ async def test_list_catalog_items_flattened_async(): @pytest.mark.asyncio async def test_list_catalog_items_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2446,7 +2325,7 @@ def test_list_catalog_items_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_catalog_items_async_pager(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2498,7 +2377,7 @@ async def test_list_catalog_items_async_pager(): @pytest.mark.asyncio async def test_list_catalog_items_async_pages(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2594,27 +2473,6 @@ def test_update_catalog_item(request_type, transport: str = "grpc"): assert response.item_group_id == "item_group_id_value" -def test_update_catalog_item_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogItemRequest() - - def test_update_catalog_item_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2684,36 +2542,6 @@ def test_update_catalog_item_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_catalog_item_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_catalog_item), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - ) - response = await client.update_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogItemRequest() - - @pytest.mark.asyncio async def test_update_catalog_item_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2722,7 +2550,7 @@ async def test_update_catalog_item_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2762,7 +2590,7 @@ async def test_update_catalog_item_async( request_type=catalog_service.UpdateCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2842,7 +2670,7 @@ def test_update_catalog_item_field_headers(): @pytest.mark.asyncio async def test_update_catalog_item_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2924,7 +2752,7 @@ def test_update_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_update_catalog_item_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2961,7 +2789,7 @@ async def test_update_catalog_item_flattened_async(): @pytest.mark.asyncio async def test_update_catalog_item_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3010,27 +2838,6 @@ def test_delete_catalog_item(request_type, transport: str = "grpc"): assert response is None -def test_delete_catalog_item_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.DeleteCatalogItemRequest() - - def test_delete_catalog_item_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3100,27 +2907,6 @@ def test_delete_catalog_item_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_catalog_item_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_catalog_item), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_catalog_item() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.DeleteCatalogItemRequest() - - @pytest.mark.asyncio async def test_delete_catalog_item_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3129,7 +2915,7 @@ async def test_delete_catalog_item_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3169,7 +2955,7 @@ async def test_delete_catalog_item_async( request_type=catalog_service.DeleteCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3234,7 +3020,7 @@ def test_delete_catalog_item_field_headers(): @pytest.mark.asyncio async def test_delete_catalog_item_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3306,7 +3092,7 @@ def test_delete_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_delete_catalog_item_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3335,7 +3121,7 @@ async def test_delete_catalog_item_flattened_async(): @pytest.mark.asyncio async def test_delete_catalog_item_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3382,27 +3168,6 @@ def test_import_catalog_items(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_catalog_items_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportCatalogItemsRequest() - - def test_import_catalog_items_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3479,29 +3244,6 @@ def test_import_catalog_items_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_catalog_items_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_catalog_items), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_catalog_items() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportCatalogItemsRequest() - - @pytest.mark.asyncio async def test_import_catalog_items_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3510,7 +3252,7 @@ async def test_import_catalog_items_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3554,7 +3296,7 @@ async def test_import_catalog_items_async( transport: str = "grpc_asyncio", request_type=import_.ImportCatalogItemsRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3621,7 +3363,7 @@ def test_import_catalog_items_field_headers(): @pytest.mark.asyncio async def test_import_catalog_items_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3722,7 +3464,7 @@ def test_import_catalog_items_flattened_error(): @pytest.mark.asyncio async def test_import_catalog_items_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3773,7 +3515,7 @@ async def test_import_catalog_items_flattened_async(): @pytest.mark.asyncio async def test_import_catalog_items_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3792,145 +3534,6 @@ async def test_import_catalog_items_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.CreateCatalogItemRequest, - dict, - ], -) -def test_create_catalog_item_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["catalog_item"] = { - "id": "id_value", - "category_hierarchies": [ - {"categories": ["categories_value1", "categories_value2"]} - ], - "title": "title_value", - "description": "description_value", - "item_attributes": {"categorical_features": {}, "numerical_features": {}}, - "language_code": "language_code_value", - "tags": ["tags_value1", "tags_value2"], - "item_group_id": "item_group_id_value", - "product_metadata": { - "exact_price": {"display_price": 0.1384, "original_price": 0.1479}, - "price_range": {"min_": 0.419, "max_": 0.421}, - "costs": {}, - "currency_code": "currency_code_value", - "stock_state": 1, - "available_quantity": 1919, - "canonical_product_uri": "canonical_product_uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.CreateCatalogItemRequest.meta.fields["catalog_item"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["catalog_item"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["catalog_item"][field])): - del request_init["catalog_item"][field][i][subfield] - else: - del request_init["catalog_item"][field][subfield] - 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 = catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CatalogItem.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_catalog_item(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == "id_value" - assert response.title == "title_value" - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.item_group_id == "item_group_id_value" - - def test_create_catalog_item_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4063,85 +3666,6 @@ def test_create_catalog_item_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_catalog_item_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_create_catalog_item" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_create_catalog_item" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.CreateCatalogItemRequest.pb( - catalog_service.CreateCatalogItemRequest() - ) - 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 = catalog.CatalogItem.to_json(catalog.CatalogItem()) - - request = catalog_service.CreateCatalogItemRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CatalogItem() - - client.create_catalog_item( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_catalog_item_rest_bad_request( - transport: str = "rest", request_type=catalog_service.CreateCatalogItemRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_catalog_item(request) - - def test_create_catalog_item_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4203,76 +3727,18 @@ def test_create_catalog_item_rest_flattened_error(transport: str = "rest"): ) -def test_create_catalog_item_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_get_catalog_item_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetCatalogItemRequest, - dict, - ], -) -def test_get_catalog_item_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - 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 = catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CatalogItem.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_catalog_item(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == "id_value" - assert response.title == "title_value" - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.item_group_id == "item_group_id_value" - - -def test_get_catalog_item_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.get_catalog_item in client._transport._wrapped_methods @@ -4382,87 +3848,6 @@ def test_get_catalog_item_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_catalog_item_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_catalog_item" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_catalog_item" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetCatalogItemRequest.pb( - catalog_service.GetCatalogItemRequest() - ) - 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 = catalog.CatalogItem.to_json(catalog.CatalogItem()) - - request = catalog_service.GetCatalogItemRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CatalogItem() - - client.get_catalog_item( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_catalog_item_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetCatalogItemRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - 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_catalog_item(request) - - def test_get_catalog_item_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4522,52 +3907,6 @@ def test_get_catalog_item_rest_flattened_error(transport: str = "rest"): ) -def test_get_catalog_item_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.ListCatalogItemsRequest, - dict, - ], -) -def test_list_catalog_items_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.ListCatalogItemsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.ListCatalogItemsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_catalog_items(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogItemsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_catalog_items_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4708,87 +4047,6 @@ def test_list_catalog_items_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_catalog_items_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalog_items" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_list_catalog_items" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.ListCatalogItemsRequest.pb( - catalog_service.ListCatalogItemsRequest() - ) - 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 = catalog_service.ListCatalogItemsResponse.to_json( - catalog_service.ListCatalogItemsResponse() - ) - - request = catalog_service.ListCatalogItemsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.ListCatalogItemsResponse() - - client.list_catalog_items( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_catalog_items_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ListCatalogItemsRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_catalog_items(request) - - def test_list_catalog_items_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4915,147 +4173,6 @@ def test_list_catalog_items_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCatalogItemRequest, - dict, - ], -) -def test_update_catalog_item_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - request_init["catalog_item"] = { - "id": "id_value", - "category_hierarchies": [ - {"categories": ["categories_value1", "categories_value2"]} - ], - "title": "title_value", - "description": "description_value", - "item_attributes": {"categorical_features": {}, "numerical_features": {}}, - "language_code": "language_code_value", - "tags": ["tags_value1", "tags_value2"], - "item_group_id": "item_group_id_value", - "product_metadata": { - "exact_price": {"display_price": 0.1384, "original_price": 0.1479}, - "price_range": {"min_": 0.419, "max_": 0.421}, - "costs": {}, - "currency_code": "currency_code_value", - "stock_state": 1, - "available_quantity": 1919, - "canonical_product_uri": "canonical_product_uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCatalogItemRequest.meta.fields["catalog_item"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["catalog_item"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["catalog_item"][field])): - del request_init["catalog_item"][field][i][subfield] - else: - del request_init["catalog_item"][field][subfield] - 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 = catalog.CatalogItem( - id="id_value", - title="title_value", - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - item_group_id="item_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CatalogItem.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_catalog_item(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CatalogItem) - assert response.id == "id_value" - assert response.title == "title_value" - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.item_group_id == "item_group_id_value" - - def test_update_catalog_item_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5190,87 +4307,6 @@ def test_update_catalog_item_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_catalog_item_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog_item" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_catalog_item" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCatalogItemRequest.pb( - catalog_service.UpdateCatalogItemRequest() - ) - 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 = catalog.CatalogItem.to_json(catalog.CatalogItem()) - - request = catalog_service.UpdateCatalogItemRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CatalogItem() - - client.update_catalog_item( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_catalog_item_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCatalogItemRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - 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_catalog_item(request) - - def test_update_catalog_item_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5334,49 +4370,6 @@ def test_update_catalog_item_rest_flattened_error(transport: str = "rest"): ) -def test_update_catalog_item_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.DeleteCatalogItemRequest, - dict, - ], -) -def test_delete_catalog_item_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_catalog_item(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_catalog_item_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5497,81 +4490,6 @@ def test_delete_catalog_item_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_catalog_item_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_delete_catalog_item" - ) as pre: - pre.assert_not_called() - pb_message = catalog_service.DeleteCatalogItemRequest.pb( - catalog_service.DeleteCatalogItemRequest() - ) - 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() - - request = catalog_service.DeleteCatalogItemRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_catalog_item( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_catalog_item_rest_bad_request( - transport: str = "rest", request_type=catalog_service.DeleteCatalogItemRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" - } - 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.delete_catalog_item(request) - - def test_delete_catalog_item_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5629,47 +4547,6 @@ def test_delete_catalog_item_rest_flattened_error(transport: str = "rest"): ) -def test_delete_catalog_item_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_.ImportCatalogItemsRequest, - dict, - ], -) -def test_import_catalog_items_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_catalog_items(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_catalog_items_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5803,6 +4680,1382 @@ def test_import_catalog_items_rest_unset_required_fields(): ) +def test_import_catalog_items_rest_flattened(): + client = CatalogServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + request_id="request_id_value", + input_config=import_.InputConfig( + catalog_inline_source=import_.CatalogInlineSource( + catalog_items=[catalog.CatalogItem(id="id_value")] + ) + ), + errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.import_catalog_items(**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/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import" + % client.transport._host, + args[1], + ) + + +def test_import_catalog_items_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent="parent_value", + request_id="request_id_value", + input_config=import_.InputConfig( + catalog_inline_source=import_.CatalogInlineSource( + catalog_items=[catalog.CatalogItem(id="id_value")] + ) + ), + errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CatalogServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_catalog_item_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), "__call__" + ) as call: + call.return_value = catalog.CatalogItem() + client.create_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.CreateCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_catalog_item_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_catalog_item), "__call__") as call: + call.return_value = catalog.CatalogItem() + client.get_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalog_items_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), "__call__" + ) as call: + call.return_value = catalog_service.ListCatalogItemsResponse() + client.list_catalog_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_item_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), "__call__" + ) as call: + call.return_value = catalog.CatalogItem() + client.update_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_catalog_item_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), "__call__" + ) as call: + call.return_value = None + client.delete_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.DeleteCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_catalog_items_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_catalog_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportCatalogItemsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CatalogServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_catalog_item_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + ) + await client.create_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.CreateCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_catalog_item_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_catalog_item), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + ) + await client.get_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_catalog_items_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.ListCatalogItemsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_catalog_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_catalog_item_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + ) + await client.update_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_catalog_item_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.DeleteCatalogItemRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_catalog_items_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_catalog_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportCatalogItemsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CatalogServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_catalog_item_rest_bad_request( + request_type=catalog_service.CreateCatalogItemRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_catalog_item(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.CreateCatalogItemRequest, + dict, + ], +) +def test_create_catalog_item_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["catalog_item"] = { + "id": "id_value", + "category_hierarchies": [ + {"categories": ["categories_value1", "categories_value2"]} + ], + "title": "title_value", + "description": "description_value", + "item_attributes": {"categorical_features": {}, "numerical_features": {}}, + "language_code": "language_code_value", + "tags": ["tags_value1", "tags_value2"], + "item_group_id": "item_group_id_value", + "product_metadata": { + "exact_price": {"display_price": 0.1384, "original_price": 0.1479}, + "price_range": {"min_": 0.419, "max_": 0.421}, + "costs": {}, + "currency_code": "currency_code_value", + "stock_state": 1, + "available_quantity": 1919, + "canonical_product_uri": "canonical_product_uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.CreateCatalogItemRequest.meta.fields["catalog_item"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["catalog_item"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["catalog_item"][field])): + del request_init["catalog_item"][field][i][subfield] + else: + del request_init["catalog_item"][field][subfield] + 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 = catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.item_group_id == "item_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_create_catalog_item" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_create_catalog_item" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.CreateCatalogItemRequest.pb( + catalog_service.CreateCatalogItemRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CatalogItem.to_json(catalog.CatalogItem()) + req.return_value.content = return_value + + request = catalog_service.CreateCatalogItemRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.create_catalog_item( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_catalog_item_rest_bad_request( + request_type=catalog_service.GetCatalogItemRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_catalog_item(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetCatalogItemRequest, + dict, + ], +) +def test_get_catalog_item_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + 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 = catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.item_group_id == "item_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_catalog_item" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_catalog_item" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetCatalogItemRequest.pb( + catalog_service.GetCatalogItemRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CatalogItem.to_json(catalog.CatalogItem()) + req.return_value.content = return_value + + request = catalog_service.GetCatalogItemRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.get_catalog_item( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_catalog_items_rest_bad_request( + request_type=catalog_service.ListCatalogItemsRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_catalog_items(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ListCatalogItemsRequest, + dict, + ], +) +def test_list_catalog_items_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.ListCatalogItemsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.ListCatalogItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_catalog_items(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_catalog_items_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalog_items" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_list_catalog_items" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ListCatalogItemsRequest.pb( + catalog_service.ListCatalogItemsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.ListCatalogItemsResponse.to_json( + catalog_service.ListCatalogItemsResponse() + ) + req.return_value.content = return_value + + request = catalog_service.ListCatalogItemsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.ListCatalogItemsResponse() + + client.list_catalog_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_catalog_item_rest_bad_request( + request_type=catalog_service.UpdateCatalogItemRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_catalog_item(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCatalogItemRequest, + dict, + ], +) +def test_update_catalog_item_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + request_init["catalog_item"] = { + "id": "id_value", + "category_hierarchies": [ + {"categories": ["categories_value1", "categories_value2"]} + ], + "title": "title_value", + "description": "description_value", + "item_attributes": {"categorical_features": {}, "numerical_features": {}}, + "language_code": "language_code_value", + "tags": ["tags_value1", "tags_value2"], + "item_group_id": "item_group_id_value", + "product_metadata": { + "exact_price": {"display_price": 0.1384, "original_price": 0.1479}, + "price_range": {"min_": 0.419, "max_": 0.421}, + "costs": {}, + "currency_code": "currency_code_value", + "stock_state": 1, + "available_quantity": 1919, + "canonical_product_uri": "canonical_product_uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCatalogItemRequest.meta.fields["catalog_item"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["catalog_item"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["catalog_item"][field])): + del request_init["catalog_item"][field][i][subfield] + else: + del request_init["catalog_item"][field][subfield] + 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 = catalog.CatalogItem( + id="id_value", + title="title_value", + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + item_group_id="item_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.item_group_id == "item_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog_item" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_catalog_item" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCatalogItemRequest.pb( + catalog_service.UpdateCatalogItemRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CatalogItem.to_json(catalog.CatalogItem()) + req.return_value.content = return_value + + request = catalog_service.UpdateCatalogItemRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.update_catalog_item( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_catalog_item_rest_bad_request( + request_type=catalog_service.DeleteCatalogItemRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_catalog_item(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.DeleteCatalogItemRequest, + dict, + ], +) +def test_delete_catalog_item_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_catalog_item(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_delete_catalog_item" + ) as pre: + pre.assert_not_called() + pb_message = catalog_service.DeleteCatalogItemRequest.pb( + catalog_service.DeleteCatalogItemRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = catalog_service.DeleteCatalogItemRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_catalog_item( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_import_catalog_items_rest_bad_request( + request_type=import_.ImportCatalogItemsRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_catalog_items(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_.ImportCatalogItemsRequest, + dict, + ], +) +def test_import_catalog_items_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_catalog_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + @pytest.mark.parametrize("null_interceptor", [True, False]) def test_import_catalog_items_rest_interceptors(null_interceptor): transport = transports.CatalogServiceRestTransport( @@ -5812,6 +6065,7 @@ def test_import_catalog_items_rest_interceptors(null_interceptor): else transports.CatalogServiceRestInterceptor(), ) client = CatalogServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5835,12 +6089,10 @@ def test_import_catalog_items_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = import_.ImportCatalogItemsRequest() metadata = [ @@ -5862,211 +6114,158 @@ def test_import_catalog_items_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_catalog_items_rest_bad_request( - transport: str = "rest", request_type=import_.ImportCatalogItemsRequest -): +def test_initialize_client_w_rest(): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.import_catalog_items(request) + assert client is not None -def test_import_catalog_items_rest_flattened(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_catalog_item_empty_call_rest(): client = CatalogServiceClient( 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), "__call__" + ) as call: + client.create_catalog_item(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.CreateCatalogItemRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - request_id="request_id_value", - input_config=import_.InputConfig( - catalog_inline_source=import_.CatalogInlineSource( - catalog_items=[catalog.CatalogItem(id="id_value")] - ) - ), - errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.import_catalog_items(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_catalog_item_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_catalog_item), "__call__") as call: + client.get_catalog_item(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCatalogItemRequest() + assert args[0] == request_msg -def test_import_catalog_items_rest_flattened_error(transport: str = "rest"): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalog_items_empty_call_rest(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_catalog_items( - import_.ImportCatalogItemsRequest(), - parent="parent_value", - request_id="request_id_value", - input_config=import_.InputConfig( - catalog_inline_source=import_.CatalogInlineSource( - catalog_items=[catalog.CatalogItem(id="id_value")] - ) - ), - errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), "__call__" + ) as call: + client.list_catalog_items(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogItemsRequest() -def test_import_catalog_items_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_item_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), "__call__" + ) as call: + client.update_catalog_item(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogItemRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_catalog_item_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), "__call__" + ) as call: + client.delete_catalog_item(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.DeleteCatalogItemRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.CatalogServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_catalog_items_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), "__call__" + ) as call: + client.import_catalog_items(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportCatalogItemsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.get_transport_class(transport_name)( + +def test_catalog_service_rest_lro_client(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -6308,23 +6507,6 @@ def test_catalog_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_catalog_service_rest_lro_client(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -6751,36 +6933,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py index 729389d26682..16c34f56d259 100644 --- a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py +++ b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import ( PredictionApiKeyRegistryAsyncClient, PredictionApiKeyRegistryClient, @@ -54,10 +63,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1241,30 +1264,6 @@ def test_create_prediction_api_key_registration(request_type, transport: str = " assert response.api_key == "api_key_value" -def test_create_prediction_api_key_registration_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - ) - - def test_create_prediction_api_key_registration_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1339,34 +1338,6 @@ def test_create_prediction_api_key_registration_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_prediction_api_key_registration_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_prediction_api_key_registration), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_apikey_registry_service.PredictionApiKeyRegistration( - api_key="api_key_value", - ) - ) - response = await client.create_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - ) - - @pytest.mark.asyncio async def test_create_prediction_api_key_registration_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1375,7 +1346,7 @@ async def test_create_prediction_api_key_registration_async_use_cached_wrapped_r # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1415,7 +1386,7 @@ async def test_create_prediction_api_key_registration_async( request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1493,7 +1464,7 @@ def test_create_prediction_api_key_registration_field_headers(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1582,7 +1553,7 @@ def test_create_prediction_api_key_registration_flattened_error(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1623,7 +1594,7 @@ async def test_create_prediction_api_key_registration_flattened_async(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1678,30 +1649,6 @@ def test_list_prediction_api_key_registrations(request_type, transport: str = "g assert response.next_page_token == "next_page_token_value" -def test_list_prediction_api_key_registrations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_prediction_api_key_registrations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - ) - - def test_list_prediction_api_key_registrations_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1778,34 +1725,6 @@ def test_list_prediction_api_key_registrations_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_prediction_api_key_registrations_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_prediction_api_key_registrations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_prediction_api_key_registrations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - ) - - @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1814,7 +1733,7 @@ async def test_list_prediction_api_key_registrations_async_use_cached_wrapped_rp # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1854,7 +1773,7 @@ async def test_list_prediction_api_key_registrations_async( request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1930,7 +1849,7 @@ def test_list_prediction_api_key_registrations_field_headers(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2008,7 +1927,7 @@ def test_list_prediction_api_key_registrations_flattened_error(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2041,7 +1960,7 @@ async def test_list_prediction_api_key_registrations_flattened_async(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2162,7 +2081,7 @@ def test_list_prediction_api_key_registrations_pages(transport_name: str = "grpc @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_async_pager(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2219,7 +2138,7 @@ async def test_list_prediction_api_key_registrations_async_pager(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_async_pages(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2304,30 +2223,6 @@ def test_delete_prediction_api_key_registration(request_type, transport: str = " assert response is None -def test_delete_prediction_api_key_registration_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - ) - - def test_delete_prediction_api_key_registration_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2402,30 +2297,6 @@ def test_delete_prediction_api_key_registration_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_prediction_api_key_registration_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_prediction_api_key_registration), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_prediction_api_key_registration() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() - ) - - @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2434,7 +2305,7 @@ async def test_delete_prediction_api_key_registration_async_use_cached_wrapped_r # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2474,7 +2345,7 @@ async def test_delete_prediction_api_key_registration_async( request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2543,7 +2414,7 @@ def test_delete_prediction_api_key_registration_field_headers(): @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2617,7 +2488,7 @@ def test_delete_prediction_api_key_registration_flattened_error(): @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2646,7 +2517,7 @@ async def test_delete_prediction_api_key_registration_flattened_async(): @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2658,54 +2529,6 @@ async def test_delete_prediction_api_key_registration_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, - dict, - ], -) -def test_create_prediction_api_key_registration_rest(request_type): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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 = prediction_apikey_registry_service.PredictionApiKeyRegistration( - api_key="api_key_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - prediction_apikey_registry_service.PredictionApiKeyRegistration.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_prediction_api_key_registration(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, prediction_apikey_registry_service.PredictionApiKeyRegistration - ) - assert response.api_key == "api_key_value" - - def test_create_prediction_api_key_registration_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2849,122 +2672,30 @@ def test_create_prediction_api_key_registration_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_prediction_api_key_registration_rest_interceptors(null_interceptor): - transport = transports.PredictionApiKeyRegistryRestTransport( +def test_create_prediction_api_key_registration_rest_flattened(): + client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionApiKeyRegistryRestInterceptor(), + transport="rest", ) - client = PredictionApiKeyRegistryClient(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.PredictionApiKeyRegistryRestInterceptor, - "post_create_prediction_api_key_registration", - ) as post, mock.patch.object( - transports.PredictionApiKeyRegistryRestInterceptor, - "pre_create_prediction_api_key_registration", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb( - prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = prediction_apikey_registry_service.PredictionApiKeyRegistration() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - prediction_apikey_registry_service.PredictionApiKeyRegistration.to_json( - prediction_apikey_registry_service.PredictionApiKeyRegistration() - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key="api_key_value" + ), ) - - request = ( - prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - prediction_apikey_registry_service.PredictionApiKeyRegistration() - ) - - client.create_prediction_api_key_registration( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_prediction_api_key_registration_rest_bad_request( - transport: str = "rest", - request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, -): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.create_prediction_api_key_registration(request) - - -def test_create_prediction_api_key_registration_rest_flattened(): - client = PredictionApiKeyRegistryClient( - 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 = prediction_apikey_registry_service.PredictionApiKeyRegistration() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration( - api_key="api_key_value" - ), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -3012,56 +2743,6 @@ def test_create_prediction_api_key_registration_rest_flattened_error( ) -def test_create_prediction_api_key_registration_rest_error(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, - dict, - ], -) -def test_list_prediction_api_key_registrations_rest(request_type): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_prediction_api_key_registrations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_prediction_api_key_registrations_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3211,96 +2892,6 @@ def test_list_prediction_api_key_registrations_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_prediction_api_key_registrations_rest_interceptors(null_interceptor): - transport = transports.PredictionApiKeyRegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionApiKeyRegistryRestInterceptor(), - ) - client = PredictionApiKeyRegistryClient(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.PredictionApiKeyRegistryRestInterceptor, - "post_list_prediction_api_key_registrations", - ) as post, mock.patch.object( - transports.PredictionApiKeyRegistryRestInterceptor, - "pre_list_prediction_api_key_registrations", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - ) - 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.to_json( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() - ) - - request = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() - ) - - client.list_prediction_api_key_registrations( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_prediction_api_key_registrations_rest_bad_request( - transport: str = "rest", - request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, -): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.list_prediction_api_key_registrations(request) - - def test_list_prediction_api_key_registrations_rest_flattened(): client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3441,43 +3032,6 @@ def test_list_prediction_api_key_registrations_rest_pager(transport: str = "rest assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, - dict, - ], -) -def test_delete_prediction_api_key_registration_rest(request_type): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_prediction_api_key_registration(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_prediction_api_key_registration_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3605,26 +3159,593 @@ def test_delete_prediction_api_key_registration_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_prediction_api_key_registration_rest_interceptors(null_interceptor): - transport = transports.PredictionApiKeyRegistryRestTransport( +def test_delete_prediction_api_key_registration_rest_flattened(): + client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionApiKeyRegistryRestInterceptor(), + transport="rest", ) - client = PredictionApiKeyRegistryClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( + + # 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5" + } + + # 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 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_prediction_api_key_registration(**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/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_prediction_api_key_registration_rest_flattened_error( + transport: str = "rest", +): + client = PredictionApiKeyRegistryClient( + 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.delete_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + transports.PredictionApiKeyRegistryRestTransport, + ], +) +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_transport_kind_grpc(): + transport = PredictionApiKeyRegistryClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_prediction_api_key_registration_empty_call_grpc(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), "__call__" + ) as call: + call.return_value = ( + prediction_apikey_registry_service.PredictionApiKeyRegistration() + ) + client.create_prediction_api_key_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_prediction_api_key_registrations_empty_call_grpc(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), "__call__" + ) as call: + call.return_value = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + ) + client.list_prediction_api_key_registrations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_prediction_api_key_registration_empty_call_grpc(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), "__call__" + ) as call: + call.return_value = None + client.delete_prediction_api_key_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PredictionApiKeyRegistryAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_empty_call_grpc_asyncio(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key="api_key_value", + ) + ) + await client.create_prediction_api_key_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_empty_call_grpc_asyncio(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_prediction_api_key_registrations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_empty_call_grpc_asyncio(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_prediction_api_key_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PredictionApiKeyRegistryClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_prediction_api_key_registration_rest_bad_request( + request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, +): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_prediction_api_key_registration(request) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, + dict, + ], +) +def test_create_prediction_api_key_registration_rest_call_success(request_type): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key="api_key_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + prediction_apikey_registry_service.PredictionApiKeyRegistration.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_prediction_api_key_registration(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, prediction_apikey_registry_service.PredictionApiKeyRegistration + ) + assert response.api_key == "api_key_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_prediction_api_key_registration_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionApiKeyRegistryRestInterceptor(), + ) + client = PredictionApiKeyRegistryClient(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.PredictionApiKeyRegistryRestInterceptor, - "pre_delete_prediction_api_key_registration", + "post_create_prediction_api_key_registration", + ) as post, mock.patch.object( + transports.PredictionApiKeyRegistryRestInterceptor, + "pre_create_prediction_api_key_registration", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ( + prediction_apikey_registry_service.PredictionApiKeyRegistration.to_json( + prediction_apikey_registry_service.PredictionApiKeyRegistration() + ) + ) + req.return_value.content = return_value + + request = ( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + prediction_apikey_registry_service.PredictionApiKeyRegistration() + ) + + client.create_prediction_api_key_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_prediction_api_key_registrations_rest_bad_request( + request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, +): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_prediction_api_key_registrations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + dict, + ], +) +def test_list_prediction_api_key_registrations_rest_call_success(request_type): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_prediction_api_key_registrations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_prediction_api_key_registrations_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionApiKeyRegistryRestInterceptor(), + ) + client = PredictionApiKeyRegistryClient(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.PredictionApiKeyRegistryRestInterceptor, + "post_list_prediction_api_key_registrations", + ) as post, mock.patch.object( + transports.PredictionApiKeyRegistryRestInterceptor, + "pre_list_prediction_api_key_registrations", ) as pre: pre.assert_not_called() - pb_message = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb( - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + post.assert_not_called() + pb_message = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() ) transcode.return_value = { "method": "post", @@ -3633,20 +3754,26 @@ def test_delete_prediction_api_key_registration_rest_interceptors(null_intercept "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() + return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.to_json( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + ) + req.return_value.content = return_value request = ( - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() ) metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + ) - client.delete_prediction_api_key_registration( + client.list_prediction_api_key_registrations( request, metadata=[ ("key", "val"), @@ -3655,17 +3782,15 @@ def test_delete_prediction_api_key_registration_rest_interceptors(null_intercept ) pre.assert_called_once() + post.assert_called_once() def test_delete_prediction_api_key_registration_rest_bad_request( - transport: str = "rest", request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5" @@ -3677,182 +3802,179 @@ def test_delete_prediction_api_key_registration_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.delete_prediction_api_key_registration(request) -def test_delete_prediction_api_key_registration_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, + dict, + ], +) +def test_delete_prediction_api_key_registration_rest_call_success(request_type): client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5" + } + 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 = None - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5" - } - - # 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 = mock.Mock() response_value.status_code = 200 json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.delete_prediction_api_key_registration(request) - client.delete_prediction_api_key_registration(**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/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert response is None -def test_delete_prediction_api_key_registration_rest_flattened_error( - transport: str = "rest", -): - client = PredictionApiKeyRegistryClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_prediction_api_key_registration_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.PredictionApiKeyRegistryRestInterceptor(), ) + client = PredictionApiKeyRegistryClient(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.PredictionApiKeyRegistryRestInterceptor, + "pre_delete_prediction_api_key_registration", + ) as pre: + pre.assert_not_called() + pb_message = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = ( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): client.delete_prediction_api_key_registration( - prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), - name="name_value", + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + -def test_delete_prediction_api_key_registration_rest_error(): +def test_initialize_client_w_rest(): client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_prediction_api_key_registration_empty_call_rest(): + client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), "__call__" + ) as call: + client.create_prediction_api_key_registration(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options=options, - transport=transport, + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_prediction_api_key_registrations_empty_call_rest(): + client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = PredictionApiKeyRegistryClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), "__call__" + ) as call: + client.list_prediction_api_key_registrations(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PredictionApiKeyRegistryClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + ) + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_prediction_api_key_registration_empty_call_rest(): + client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PredictionApiKeyRegistryGrpcTransport, - transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, - transports.PredictionApiKeyRegistryRestTransport, - ], -) -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() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), "__call__" + ) as call: + client.delete_prediction_api_key_registration(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + ) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PredictionApiKeyRegistryClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name + assert args[0] == request_msg def test_transport_grpc_default(): @@ -4485,36 +4607,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PredictionApiKeyRegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py index 4d146266b0b3..6050dbd5a1e5 100644 --- a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py +++ b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -22,28 +22,37 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth 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 from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -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.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1204,25 +1227,6 @@ def test_predict(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - def test_predict_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,39 +1294,13 @@ def test_predict_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_predict_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_service.PredictResponse( - recommendation_token="recommendation_token_value", - items_missing_in_catalog=["items_missing_in_catalog_value"], - dry_run=True, - next_page_token="next_page_token_value", - ) - ) - response = await client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - @pytest.mark.asyncio async def test_predict_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1361,7 +1339,7 @@ async def test_predict_async( transport: str = "grpc_asyncio", request_type=prediction_service.PredictRequest ): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1411,7 @@ def test_predict_field_headers(): @pytest.mark.asyncio async def test_predict_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1508,7 +1486,7 @@ def test_predict_flattened_error(): @pytest.mark.asyncio async def test_predict_flattened_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1541,7 +1519,7 @@ async def test_predict_flattened_async(): @pytest.mark.asyncio async def test_predict_flattened_error_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1655,7 +1633,7 @@ def test_predict_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_predict_async_pager(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1708,7 +1686,7 @@ async def test_predict_async_pager(): @pytest.mark.asyncio async def test_predict_async_pages(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1754,54 +1732,6 @@ async def test_predict_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - prediction_service.PredictRequest, - dict, - ], -) -def test_predict_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5" - } - 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 = prediction_service.PredictResponse( - recommendation_token="recommendation_token_value", - items_missing_in_catalog=["items_missing_in_catalog_value"], - dry_run=True, - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = prediction_service.PredictResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.predict(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.PredictPager) - assert response.recommendation_token == "recommendation_token_value" - assert response.items_missing_in_catalog == ["items_missing_in_catalog_value"] - assert response.dry_run is True - assert response.next_page_token == "next_page_token_value" - - def test_predict_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1928,89 +1858,6 @@ def test_predict_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_predict_rest_interceptors(null_interceptor): - transport = transports.PredictionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionServiceRestInterceptor(), - ) - client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" - ) as post, mock.patch.object( - transports.PredictionServiceRestInterceptor, "pre_predict" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_service.PredictRequest.pb( - prediction_service.PredictRequest() - ) - 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 = prediction_service.PredictResponse.to_json( - prediction_service.PredictResponse() - ) - - request = prediction_service.PredictRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = prediction_service.PredictResponse() - - client.predict( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_predict_rest_bad_request( - transport: str = "rest", request_type=prediction_service.PredictRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5" - } - 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.predict(request) - - def test_predict_rest_flattened(): client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2232,18 +2079,246 @@ def test_transport_adc(transport_class): adc.assert_called_once() +def test_transport_kind_grpc(): + transport = PredictionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = PredictionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_predict_empty_call_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_service.PredictResponse( + recommendation_token="recommendation_token_value", + items_missing_in_catalog=["items_missing_in_catalog_value"], + dry_run=True, + next_page_token="next_page_token_value", + ) + ) + await client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PredictionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_predict_rest_bad_request(request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.predict(request) + + @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + prediction_service.PredictRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.get_transport_class(transport_name)( +def test_predict_rest_call_success(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5" + } + 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 = prediction_service.PredictResponse( + recommendation_token="recommendation_token_value", + items_missing_in_catalog=["items_missing_in_catalog_value"], + dry_run=True, + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.predict(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PredictPager) + assert response.recommendation_token == "recommendation_token_value" + assert response.items_missing_in_catalog == ["items_missing_in_catalog_value"] + assert response.dry_run is True + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_predict_rest_interceptors(null_interceptor): + transport = transports.PredictionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionServiceRestInterceptor(), + ) + client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" + ) as post, mock.patch.object( + transports.PredictionServiceRestInterceptor, "pre_predict" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_service.PredictRequest.pb( + prediction_service.PredictRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = prediction_service.PredictResponse.to_json( + prediction_service.PredictResponse() + ) + req.return_value.content = return_value + + request = prediction_service.PredictRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_service.PredictResponse() + + client.predict( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_rest(): + client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -2827,36 +2902,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py index 606f8a8f4131..6ee3e9ade0b8 100644 --- a/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py +++ b/packages/google-cloud-recommendations-ai/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import httpbody_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.recommendationengine_v1beta1.services.user_event_service import ( UserEventServiceAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.recommendationengine_v1beta1.types import user_event_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1201,25 +1224,6 @@ def test_write_user_event(request_type, transport: str = "grpc"): assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - def test_write_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1285,30 +1289,6 @@ def test_write_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_write_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_user_event.UserEvent( - event_type="event_type_value", - event_source=gcr_user_event.UserEvent.EventSource.AUTOML, - ) - ) - response = await client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - @pytest.mark.asyncio async def test_write_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1317,7 +1297,7 @@ async def test_write_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1357,7 +1337,7 @@ async def test_write_user_event_async( request_type=user_event_service.WriteUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1425,7 +1405,7 @@ def test_write_user_event_field_headers(): @pytest.mark.asyncio async def test_write_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1500,7 +1480,7 @@ def test_write_user_event_flattened_error(): @pytest.mark.asyncio async def test_write_user_event_flattened_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1533,7 +1513,7 @@ async def test_write_user_event_flattened_async(): @pytest.mark.asyncio async def test_write_user_event_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1586,27 +1566,6 @@ def test_collect_user_event(request_type, transport: str = "grpc"): assert response.data == b"data_blob" -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - def test_collect_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1680,32 +1639,6 @@ def test_collect_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_collect_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - ) - response = await client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - @pytest.mark.asyncio async def test_collect_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1714,7 +1647,7 @@ async def test_collect_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1754,7 +1687,7 @@ async def test_collect_user_event_async( request_type=user_event_service.CollectUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1826,7 +1759,7 @@ def test_collect_user_event_field_headers(): @pytest.mark.asyncio async def test_collect_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1915,7 +1848,7 @@ def test_collect_user_event_flattened_error(): @pytest.mark.asyncio async def test_collect_user_event_flattened_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1958,7 +1891,7 @@ async def test_collect_user_event_flattened_async(): @pytest.mark.asyncio async def test_collect_user_event_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2009,25 +1942,6 @@ def test_list_user_events(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.ListUserEventsRequest() - - def test_list_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2097,29 +2011,6 @@ def test_list_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - user_event_service.ListUserEventsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.ListUserEventsRequest() - - @pytest.mark.asyncio async def test_list_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2128,7 +2019,7 @@ async def test_list_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2168,7 +2059,7 @@ async def test_list_user_events_async( request_type=user_event_service.ListUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2234,7 +2125,7 @@ def test_list_user_events_field_headers(): @pytest.mark.asyncio async def test_list_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2309,7 +2200,7 @@ def test_list_user_events_flattened_error(): @pytest.mark.asyncio async def test_list_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2342,7 +2233,7 @@ async def test_list_user_events_flattened_async(): @pytest.mark.asyncio async def test_list_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2453,7 +2344,7 @@ def test_list_user_events_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_user_events_async_pager(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2503,7 +2394,7 @@ async def test_list_user_events_async_pager(): @pytest.mark.asyncio async def test_list_user_events_async_pages(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2584,27 +2475,6 @@ def test_purge_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.PurgeUserEventsRequest() - - def test_purge_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2679,29 +2549,6 @@ def test_purge_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.PurgeUserEventsRequest() - - @pytest.mark.asyncio async def test_purge_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2710,7 +2557,7 @@ async def test_purge_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2755,7 +2602,7 @@ async def test_purge_user_events_async( request_type=user_event_service.PurgeUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2822,7 +2669,7 @@ def test_purge_user_events_field_headers(): @pytest.mark.asyncio async def test_purge_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2906,7 +2753,7 @@ def test_purge_user_events_flattened_error(): @pytest.mark.asyncio async def test_purge_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2945,7 +2792,7 @@ async def test_purge_user_events_flattened_async(): @pytest.mark.asyncio async def test_purge_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2994,27 +2841,6 @@ def test_import_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportUserEventsRequest() - - def test_import_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3091,29 +2917,6 @@ def test_import_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportUserEventsRequest() - - @pytest.mark.asyncio async def test_import_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3122,7 +2925,7 @@ async def test_import_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3166,7 +2969,7 @@ async def test_import_user_events_async( transport: str = "grpc_asyncio", request_type=import_.ImportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3233,7 +3036,7 @@ def test_import_user_events_field_headers(): @pytest.mark.asyncio async def test_import_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3334,7 +3137,7 @@ def test_import_user_events_flattened_error(): @pytest.mark.asyncio async def test_import_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3385,7 +3188,7 @@ async def test_import_user_events_flattened_async(): @pytest.mark.asyncio async def test_import_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3404,172 +3207,14 @@ async def test_import_user_events_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.WriteUserEventRequest, - dict, - ], -) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - request_init["user_event"] = { - "event_type": "event_type_value", - "user_info": { - "visitor_id": "visitor_id_value", - "user_id": "user_id_value", - "ip_address": "ip_address_value", - "user_agent": "user_agent_value", - "direct_user_request": True, - }, - "event_detail": { - "uri": "uri_value", - "referrer_uri": "referrer_uri_value", - "page_view_id": "page_view_id_value", - "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], - "recommendation_token": "recommendation_token_value", - "event_attributes": {"categorical_features": {}, "numerical_features": {}}, - }, - "product_event_detail": { - "search_query": "search_query_value", - "page_categories": [ - {"categories": ["categories_value1", "categories_value2"]} - ], - "product_details": [ - { - "id": "id_value", - "currency_code": "currency_code_value", - "original_price": 0.1479, - "display_price": 0.1384, - "stock_state": 1, - "quantity": 895, - "available_quantity": 1919, - "item_attributes": {}, - } - ], - "list_id": "list_id_value", - "cart_id": "cart_id_value", - "purchase_transaction": { - "id": "id_value", - "revenue": 0.762, - "taxes": {}, - "costs": {}, - "currency_code": "currency_code_value", - }, - }, - "event_time": {"seconds": 751, "nanos": 543}, - "event_source": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["user_event"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["user_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][field][subfield] - 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 = gcr_user_event.UserEvent( - event_type="event_type_value", - event_source=gcr_user_event.UserEvent.EventSource.AUTOML, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_user_event.UserEvent) - assert response.event_type == "event_type_value" - assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML - - -def test_write_user_event_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_write_user_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3692,89 +3337,6 @@ def test_write_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_write_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb( - user_event_service.WriteUserEventRequest() - ) - 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 = gcr_user_event.UserEvent.to_json( - gcr_user_event.UserEvent() - ) - - request = user_event_service.WriteUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_user_event.UserEvent() - - client.write_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.WriteUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.write_user_event(request) - - def test_write_user_event_rest_flattened(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3836,71 +3398,23 @@ def test_write_user_event_rest_flattened_error(transport: str = "rest"): ) -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_collect_user_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.CollectUserEventRequest, - dict, - ], -) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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 = httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == "content_type_value" - assert response.data == b"data_blob" - - -def test_collect_user_event_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.collect_user_event in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.collect_user_event in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -4040,87 +3554,6 @@ def test_collect_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_collect_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb( - user_event_service.CollectUserEventRequest() - ) - 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.CollectUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.collect_user_event(request) - - def test_collect_user_event_rest_flattened(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4184,54 +3617,6 @@ def test_collect_user_event_rest_flattened_error(transport: str = "rest"): ) -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.ListUserEventsRequest, - dict, - ], -) -def test_list_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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_event_service.ListUserEventsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = user_event_service.ListUserEventsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_user_events(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserEventsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4370,89 +3755,6 @@ def test_list_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_list_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_list_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.ListUserEventsRequest.pb( - user_event_service.ListUserEventsRequest() - ) - 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_event_service.ListUserEventsResponse.to_json( - user_event_service.ListUserEventsResponse() - ) - - request = user_event_service.ListUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event_service.ListUserEventsResponse() - - client.list_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_user_events_rest_bad_request( - transport: str = "rest", request_type=user_event_service.ListUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.list_user_events(request) - - def test_list_user_events_rest_flattened(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4579,51 +3881,14 @@ def test_list_user_events_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.PurgeUserEventsRequest, - dict, - ], -) -def test_purge_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_purge_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -4751,91 +4016,6 @@ def test_purge_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_purge_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_purge_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.PurgeUserEventsRequest.pb( - user_event_service.PurgeUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = user_event_service.PurgeUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_user_events_rest_bad_request( - transport: str = "rest", request_type=user_event_service.PurgeUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.purge_user_events(request) - - def test_purge_user_events_rest_flattened(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4897,49 +4077,6 @@ def test_purge_user_events_rest_flattened_error(transport: str = "rest"): ) -def test_purge_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_.ImportUserEventsRequest, - dict, - ], -) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5061,16 +4198,1130 @@ def test_import_user_events_rest_unset_required_fields(): credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.import_user_events._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) - ) + unset_fields = transport.import_user_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "inputConfig", + ) + ) + ) + + +def test_import_user_events_rest_flattened(): + client = UserEventServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + request_id="request_id_value", + input_config=import_.InputConfig( + catalog_inline_source=import_.CatalogInlineSource( + catalog_items=[catalog.CatalogItem(id="id_value")] + ) + ), + errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.import_user_events(**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/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import" + % client.transport._host, + args[1], + ) + + +def test_import_user_events_rest_flattened_error(transport: str = "rest"): + client = UserEventServiceClient( + 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.import_user_events( + import_.ImportUserEventsRequest(), + parent="parent_value", + request_id="request_id_value", + input_config=import_.InputConfig( + catalog_inline_source=import_.CatalogInlineSource( + catalog_items=[catalog.CatalogItem(id="id_value")] + ) + ), + errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = UserEventServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + call.return_value = gcr_user_event.UserEvent() + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: + call.return_value = user_event_service.ListUserEventsResponse() + client.list_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.ListUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserEventServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_write_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_user_event.UserEvent( + event_type="event_type_value", + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + ) + ) + await client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_collect_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + ) + await client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user_event_service.ListUserEventsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.ListUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserEventServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_write_user_event_rest_bad_request( + request_type=user_event_service.WriteUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.write_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.WriteUserEventRequest, + dict, + ], +) +def test_write_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + request_init["user_event"] = { + "event_type": "event_type_value", + "user_info": { + "visitor_id": "visitor_id_value", + "user_id": "user_id_value", + "ip_address": "ip_address_value", + "user_agent": "user_agent_value", + "direct_user_request": True, + }, + "event_detail": { + "uri": "uri_value", + "referrer_uri": "referrer_uri_value", + "page_view_id": "page_view_id_value", + "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], + "recommendation_token": "recommendation_token_value", + "event_attributes": {"categorical_features": {}, "numerical_features": {}}, + }, + "product_event_detail": { + "search_query": "search_query_value", + "page_categories": [ + {"categories": ["categories_value1", "categories_value2"]} + ], + "product_details": [ + { + "id": "id_value", + "currency_code": "currency_code_value", + "original_price": 0.1479, + "display_price": 0.1384, + "stock_state": 1, + "quantity": 895, + "available_quantity": 1919, + "item_attributes": {}, + } + ], + "list_id": "list_id_value", + "cart_id": "cart_id_value", + "purchase_transaction": { + "id": "id_value", + "revenue": 0.762, + "taxes": {}, + "costs": {}, + "currency_code": "currency_code_value", + }, + }, + "event_time": {"seconds": 751, "nanos": 543}, + "event_source": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][field][subfield] + 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 = gcr_user_event.UserEvent( + event_type="event_type_value", + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_user_event.UserEvent) + assert response.event_type == "event_type_value" + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_write_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb( + user_event_service.WriteUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_user_event.UserEvent.to_json(gcr_user_event.UserEvent()) + req.return_value.content = return_value + + request = user_event_service.WriteUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_user_event.UserEvent() + + client.write_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request( + request_type=user_event_service.CollectUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.collect_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.CollectUserEventRequest, + dict, + ], +) +def test_collect_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == "content_type_value" + assert response.data == b"data_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_collect_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb( + user_event_service.CollectUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(httpbody_pb2.HttpBody()) + req.return_value.content = return_value + + request = user_event_service.CollectUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_events_rest_bad_request( + request_type=user_event_service.ListUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.ListUserEventsRequest, + dict, + ], +) +def test_list_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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_event_service.ListUserEventsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = user_event_service.ListUserEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_user_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_list_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_list_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.ListUserEventsRequest.pb( + user_event_service.ListUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = user_event_service.ListUserEventsResponse.to_json( + user_event_service.ListUserEventsResponse() + ) + req.return_value.content = return_value + + request = user_event_service.ListUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event_service.ListUserEventsResponse() + + client.list_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request( + request_type=user_event_service.PurgeUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.PurgeUserEventsRequest, + dict, + ], +) +def test_purge_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_purge_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_purge_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.PurgeUserEventsRequest.pb( + user_event_service.PurgeUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = user_event_service.PurgeUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request( + request_type=import_.ImportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_.ImportUserEventsRequest, + dict, + ], +) +def test_import_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5082,6 +5333,7 @@ def test_import_user_events_rest_interceptors(null_interceptor): else transports.UserEventServiceRestInterceptor(), ) client = UserEventServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5105,12 +5357,10 @@ def test_import_user_events_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = import_.ImportUserEventsRequest() metadata = [ @@ -5132,213 +5382,134 @@ def test_import_user_events_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_user_events_rest_bad_request( - transport: str = "rest", request_type=import_.ImportUserEventsRequest -): +def test_initialize_client_w_rest(): client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - 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.import_user_events(request) + assert client is not None -def test_import_user_events_rest_flattened(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_rest(): client = UserEventServiceClient( 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - request_id="request_id_value", - input_config=import_.InputConfig( - catalog_inline_source=import_.CatalogInlineSource( - catalog_items=[catalog.CatalogItem(id="id_value")] - ) - ), - errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + client.write_user_event(request=None) - client.import_user_events(**mock_args) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() - # 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/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import" - % client.transport._host, - args[1], - ) + assert args[0] == request_msg -def test_import_user_events_rest_flattened_error(transport: str = "rest"): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_rest(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.import_user_events( - import_.ImportUserEventsRequest(), - parent="parent_value", - request_id="request_id_value", - input_config=import_.InputConfig( - catalog_inline_source=import_.CatalogInlineSource( - catalog_items=[catalog.CatalogItem(id="id_value")] - ) - ), - errors_config=import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value"), - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + client.collect_user_event(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: + client.list_user_events(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.ListUserEventsRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + client.purge_user_events(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.PurgeUserEventsRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.UserEventServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + client.import_user_events(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_.ImportUserEventsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -5579,23 +5750,6 @@ def test_user_event_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -5993,36 +6147,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/README.rst b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/README.rst new file mode 100644 index 000000000000..c050545fb138 --- /dev/null +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RecommenderTransport` is the ABC for all transports. +- public child `RecommenderGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RecommenderGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRecommenderRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RecommenderRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py index 2fba0f75e640..413fbd3463c0 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -240,6 +241,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -687,7 +691,7 @@ def update_insight_type_config( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_insights: gapic_v1.method_async.wrap_method( + self.list_insights: self._wrap_method( self.list_insights, default_retry=retries.AsyncRetry( initial=0.1, @@ -702,7 +706,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_insight: gapic_v1.method_async.wrap_method( + self.get_insight: self._wrap_method( self.get_insight, default_retry=retries.AsyncRetry( initial=0.1, @@ -717,12 +721,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.mark_insight_accepted: gapic_v1.method_async.wrap_method( + self.mark_insight_accepted: self._wrap_method( self.mark_insight_accepted, default_timeout=60.0, client_info=client_info, ), - self.list_recommendations: gapic_v1.method_async.wrap_method( + self.list_recommendations: self._wrap_method( self.list_recommendations, default_retry=retries.AsyncRetry( initial=0.1, @@ -737,7 +741,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_recommendation: gapic_v1.method_async.wrap_method( + self.get_recommendation: self._wrap_method( self.get_recommendation, default_retry=retries.AsyncRetry( initial=0.1, @@ -752,50 +756,59 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_dismissed: gapic_v1.method_async.wrap_method( + self.mark_recommendation_dismissed: self._wrap_method( self.mark_recommendation_dismissed, default_timeout=None, client_info=client_info, ), - self.mark_recommendation_claimed: gapic_v1.method_async.wrap_method( + self.mark_recommendation_claimed: self._wrap_method( self.mark_recommendation_claimed, default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_succeeded: gapic_v1.method_async.wrap_method( + self.mark_recommendation_succeeded: self._wrap_method( self.mark_recommendation_succeeded, default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_failed: gapic_v1.method_async.wrap_method( + self.mark_recommendation_failed: self._wrap_method( self.mark_recommendation_failed, default_timeout=60.0, client_info=client_info, ), - self.get_recommender_config: gapic_v1.method_async.wrap_method( + self.get_recommender_config: self._wrap_method( self.get_recommender_config, default_timeout=None, client_info=client_info, ), - self.update_recommender_config: gapic_v1.method_async.wrap_method( + self.update_recommender_config: self._wrap_method( self.update_recommender_config, default_timeout=None, client_info=client_info, ), - self.get_insight_type_config: gapic_v1.method_async.wrap_method( + self.get_insight_type_config: self._wrap_method( self.get_insight_type_config, default_timeout=None, client_info=client_info, ), - self.update_insight_type_config: gapic_v1.method_async.wrap_method( + self.update_insight_type_config: self._wrap_method( self.update_insight_type_config, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("RecommenderGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest.py index 65fd8c2494d8..aa826aee6590 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest.py @@ -16,26 +16,17 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.cloud.recommender_v1.types import ( insight_type_config as gcr_insight_type_config, ) @@ -49,7 +40,13 @@ from google.cloud.recommender_v1.types import recommender_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import RecommenderTransport +from .rest_base import _BaseRecommenderRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -508,8 +505,8 @@ class RecommenderRestStub: _interceptor: RecommenderRestInterceptor -class RecommenderRestTransport(RecommenderTransport): - """REST backend transport for Recommender. +class RecommenderRestTransport(_BaseRecommenderRestTransport): + """REST backend synchronous transport for Recommender. Provides insights and recommendations for cloud customers for various categories like performance optimization, cost savings, @@ -522,7 +519,6 @@ class RecommenderRestTransport(RecommenderTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -576,21 +572,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -601,19 +588,33 @@ def __init__( self._interceptor = interceptor or RecommenderRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetInsight(RecommenderRestStub): + class _GetInsight( + _BaseRecommenderRestTransport._BaseGetInsight, RecommenderRestStub + ): def __hash__(self): - return hash("GetInsight") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetInsight") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -643,50 +644,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/insights/*}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_http_options() + ) request, metadata = self._interceptor.pre_get_insight(request, metadata) - pb_request = recommender_service.GetInsightRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetInsight._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -702,19 +684,33 @@ def __call__( resp = self._interceptor.post_get_insight(resp) return resp - class _GetInsightTypeConfig(RecommenderRestStub): + class _GetInsightTypeConfig( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig, RecommenderRestStub + ): def __hash__(self): - return hash("GetInsightTypeConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetInsightTypeConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -740,48 +736,29 @@ def __call__( Configuration for an InsightType. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/config}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/config}", - }, - { - "method": "get", - "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/config}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_insight_type_config( request, metadata ) - pb_request = recommender_service.GetInsightTypeConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetInsightTypeConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -797,19 +774,33 @@ def __call__( resp = self._interceptor.post_get_insight_type_config(resp) return resp - class _GetRecommendation(RecommenderRestStub): + class _GetRecommendation( + _BaseRecommenderRestTransport._BaseGetRecommendation, RecommenderRestStub + ): def __hash__(self): - return hash("GetRecommendation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetRecommendation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -839,52 +830,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetRecommendation._get_http_options() + ) request, metadata = self._interceptor.pre_get_recommendation( request, metadata ) - pb_request = recommender_service.GetRecommendationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetRecommendation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetRecommendation._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetRecommendation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -900,19 +868,33 @@ def __call__( resp = self._interceptor.post_get_recommendation(resp) return resp - class _GetRecommenderConfig(RecommenderRestStub): + class _GetRecommenderConfig( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig, RecommenderRestStub + ): def __hash__(self): - return hash("GetRecommenderConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetRecommenderConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -938,48 +920,29 @@ def __call__( Configuration for a Recommender. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/config}", - }, - { - "method": "get", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/config}", - }, - { - "method": "get", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/config}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_recommender_config( request, metadata ) - pb_request = recommender_service.GetRecommenderConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetRecommenderConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -995,19 +958,33 @@ def __call__( resp = self._interceptor.post_get_recommender_config(resp) return resp - class _ListInsights(RecommenderRestStub): + class _ListInsights( + _BaseRecommenderRestTransport._BaseListInsights, RecommenderRestStub + ): def __hash__(self): - return hash("ListInsights") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.ListInsights") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1033,50 +1010,31 @@ def __call__( Response to the ``ListInsights`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1/{parent=billingAccounts/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*/insightTypes/*}/insights", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListInsights._get_http_options() + ) request, metadata = self._interceptor.pre_list_insights(request, metadata) - pb_request = recommender_service.ListInsightsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRecommenderRestTransport._BaseListInsights._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRecommenderRestTransport._BaseListInsights._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._ListInsights._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1092,19 +1050,33 @@ def __call__( resp = self._interceptor.post_list_insights(resp) return resp - class _ListRecommendations(RecommenderRestStub): + class _ListRecommendations( + _BaseRecommenderRestTransport._BaseListRecommendations, RecommenderRestStub + ): def __hash__(self): - return hash("ListRecommendations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.ListRecommendations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1130,52 +1102,29 @@ def __call__( Response to the ``ListRecommendations`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1/{parent=billingAccounts/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1/{parent=organizations/*/locations/*/recommenders/*}/recommendations", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListRecommendations._get_http_options() + ) request, metadata = self._interceptor.pre_list_recommendations( request, metadata ) - pb_request = recommender_service.ListRecommendationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseListRecommendations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseListRecommendations._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._ListRecommendations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1191,19 +1140,34 @@ def __call__( resp = self._interceptor.post_list_recommendations(resp) return resp - class _MarkInsightAccepted(RecommenderRestStub): + class _MarkInsightAccepted( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted, RecommenderRestStub + ): def __hash__(self): - return hash("MarkInsightAccepted") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkInsightAccepted") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1233,62 +1197,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_http_options() + ) request, metadata = self._interceptor.pre_mark_insight_accepted( request, metadata ) - pb_request = recommender_service.MarkInsightAcceptedRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._MarkInsightAccepted._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1304,19 +1240,35 @@ def __call__( resp = self._interceptor.post_mark_insight_accepted(resp) return resp - class _MarkRecommendationClaimed(RecommenderRestStub): + class _MarkRecommendationClaimed( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed, + RecommenderRestStub, + ): def __hash__(self): - return hash("MarkRecommendationClaimed") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationClaimed") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1347,64 +1299,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_claimed( request, metadata ) - pb_request = recommender_service.MarkRecommendationClaimedRequest.pb( - request + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RecommenderRestTransport._MarkRecommendationClaimed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1420,19 +1344,35 @@ def __call__( resp = self._interceptor.post_mark_recommendation_claimed(resp) return resp - class _MarkRecommendationDismissed(RecommenderRestStub): + class _MarkRecommendationDismissed( + _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed, + RecommenderRestStub, + ): def __hash__(self): - return hash("MarkRecommendationDismissed") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationDismissed") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1463,64 +1403,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markDismissed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markDismissed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markDismissed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markDismissed", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_dismissed( request, metadata ) - pb_request = recommender_service.MarkRecommendationDismissedRequest.pb( - request + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RecommenderRestTransport._MarkRecommendationDismissed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1536,19 +1448,34 @@ def __call__( resp = self._interceptor.post_mark_recommendation_dismissed(resp) return resp - class _MarkRecommendationFailed(RecommenderRestStub): + class _MarkRecommendationFailed( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed, RecommenderRestStub + ): def __hash__(self): - return hash("MarkRecommendationFailed") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationFailed") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1579,62 +1506,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_failed( request, metadata ) - pb_request = recommender_service.MarkRecommendationFailedRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._MarkRecommendationFailed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1650,19 +1549,35 @@ def __call__( resp = self._interceptor.post_mark_recommendation_failed(resp) return resp - class _MarkRecommendationSucceeded(RecommenderRestStub): + class _MarkRecommendationSucceeded( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded, + RecommenderRestStub, + ): def __hash__(self): - return hash("MarkRecommendationSucceeded") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationSucceeded") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1693,64 +1608,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_succeeded( request, metadata ) - pb_request = recommender_service.MarkRecommendationSucceededRequest.pb( - request + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RecommenderRestTransport._MarkRecommendationSucceeded._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1766,19 +1653,34 @@ def __call__( resp = self._interceptor.post_mark_recommendation_succeeded(resp) return resp - class _UpdateInsightTypeConfig(RecommenderRestStub): + class _UpdateInsightTypeConfig( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig, RecommenderRestStub + ): def __hash__(self): - return hash("UpdateInsightTypeConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.UpdateInsightTypeConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1805,57 +1707,34 @@ def __call__( Configuration for an InsightType. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}", - "body": "insight_type_config", - }, - { - "method": "patch", - "uri": "/v1/{insight_type_config.name=organizations/*/locations/*/insightTypes/*/config}", - "body": "insight_type_config", - }, - { - "method": "patch", - "uri": "/v1/{insight_type_config.name=billingAccounts/*/locations/*/insightTypes/*/config}", - "body": "insight_type_config", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_insight_type_config( request, metadata ) - pb_request = recommender_service.UpdateInsightTypeConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._UpdateInsightTypeConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1871,19 +1750,34 @@ def __call__( resp = self._interceptor.post_update_insight_type_config(resp) return resp - class _UpdateRecommenderConfig(RecommenderRestStub): + class _UpdateRecommenderConfig( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig, RecommenderRestStub + ): def __hash__(self): - return hash("UpdateRecommenderConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.UpdateRecommenderConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1909,57 +1803,34 @@ def __call__( Configuration for a Recommender. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{recommender_config.name=projects/*/locations/*/recommenders/*/config}", - "body": "recommender_config", - }, - { - "method": "patch", - "uri": "/v1/{recommender_config.name=organizations/*/locations/*/recommenders/*/config}", - "body": "recommender_config", - }, - { - "method": "patch", - "uri": "/v1/{recommender_config.name=billingAccounts/*/locations/*/recommenders/*/config}", - "body": "recommender_config", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_recommender_config( request, metadata ) - pb_request = recommender_service.UpdateRecommenderConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._UpdateRecommenderConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest_base.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest_base.py new file mode 100644 index 000000000000..b946ff496bea --- /dev/null +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/services/recommender/transports/rest_base.py @@ -0,0 +1,947 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.recommender_v1.types import ( + insight_type_config as gcr_insight_type_config, +) +from google.cloud.recommender_v1.types import ( + recommender_config as gcr_recommender_config, +) +from google.cloud.recommender_v1.types import insight +from google.cloud.recommender_v1.types import insight_type_config +from google.cloud.recommender_v1.types import recommendation +from google.cloud.recommender_v1.types import recommender_config +from google.cloud.recommender_v1.types import recommender_service + +from .base import DEFAULT_CLIENT_INFO, RecommenderTransport + + +class _BaseRecommenderRestTransport(RecommenderTransport): + """Base REST backend transport for Recommender. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommender.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetInsight: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/insights/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetInsightRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetInsight._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInsightTypeConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/config}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/config}", + }, + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/config}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetInsightTypeConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRecommendation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetRecommendationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetRecommendation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRecommenderConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/config}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/config}", + }, + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/config}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetRecommenderConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInsights: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1/{parent=billingAccounts/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/insightTypes/*}/insights", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListInsightsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseListInsights._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRecommendations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1/{parent=billingAccounts/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/recommenders/*}/recommendations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListRecommendationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseListRecommendations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkInsightAccepted: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkInsightAcceptedRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationClaimed: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationClaimedRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationDismissed: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markDismissed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markDismissed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markDismissed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markDismissed", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationDismissedRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationDismissed._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationFailed: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationFailedRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationSucceeded: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationSucceededRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInsightTypeConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}", + "body": "insight_type_config", + }, + { + "method": "patch", + "uri": "/v1/{insight_type_config.name=organizations/*/locations/*/insightTypes/*/config}", + "body": "insight_type_config", + }, + { + "method": "patch", + "uri": "/v1/{insight_type_config.name=billingAccounts/*/locations/*/insightTypes/*/config}", + "body": "insight_type_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.UpdateInsightTypeConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateRecommenderConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{recommender_config.name=projects/*/locations/*/recommenders/*/config}", + "body": "recommender_config", + }, + { + "method": "patch", + "uri": "/v1/{recommender_config.name=organizations/*/locations/*/recommenders/*/config}", + "body": "recommender_config", + }, + { + "method": "patch", + "uri": "/v1/{recommender_config.name=billingAccounts/*/locations/*/recommenders/*/config}", + "body": "recommender_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.UpdateRecommenderConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseRecommenderRestTransport",) diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/README.rst b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/README.rst new file mode 100644 index 000000000000..c050545fb138 --- /dev/null +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RecommenderTransport` is the ABC for all transports. +- public child `RecommenderGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RecommenderGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRecommenderRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RecommenderRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py index 940eb2a5ff5b..c3d1f32f3027 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -240,6 +241,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -708,7 +712,7 @@ def list_insight_types( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_insights: gapic_v1.method_async.wrap_method( + self.list_insights: self._wrap_method( self.list_insights, default_retry=retries.AsyncRetry( initial=0.1, @@ -723,7 +727,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_insight: gapic_v1.method_async.wrap_method( + self.get_insight: self._wrap_method( self.get_insight, default_retry=retries.AsyncRetry( initial=0.1, @@ -738,12 +742,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.mark_insight_accepted: gapic_v1.method_async.wrap_method( + self.mark_insight_accepted: self._wrap_method( self.mark_insight_accepted, default_timeout=60.0, client_info=client_info, ), - self.list_recommendations: gapic_v1.method_async.wrap_method( + self.list_recommendations: self._wrap_method( self.list_recommendations, default_retry=retries.AsyncRetry( initial=0.1, @@ -758,7 +762,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_recommendation: gapic_v1.method_async.wrap_method( + self.get_recommendation: self._wrap_method( self.get_recommendation, default_retry=retries.AsyncRetry( initial=0.1, @@ -773,55 +777,64 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_claimed: gapic_v1.method_async.wrap_method( + self.mark_recommendation_claimed: self._wrap_method( self.mark_recommendation_claimed, default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_succeeded: gapic_v1.method_async.wrap_method( + self.mark_recommendation_succeeded: self._wrap_method( self.mark_recommendation_succeeded, default_timeout=60.0, client_info=client_info, ), - self.mark_recommendation_failed: gapic_v1.method_async.wrap_method( + self.mark_recommendation_failed: self._wrap_method( self.mark_recommendation_failed, default_timeout=60.0, client_info=client_info, ), - self.get_recommender_config: gapic_v1.method_async.wrap_method( + self.get_recommender_config: self._wrap_method( self.get_recommender_config, default_timeout=None, client_info=client_info, ), - self.update_recommender_config: gapic_v1.method_async.wrap_method( + self.update_recommender_config: self._wrap_method( self.update_recommender_config, default_timeout=None, client_info=client_info, ), - self.get_insight_type_config: gapic_v1.method_async.wrap_method( + self.get_insight_type_config: self._wrap_method( self.get_insight_type_config, default_timeout=None, client_info=client_info, ), - self.update_insight_type_config: gapic_v1.method_async.wrap_method( + self.update_insight_type_config: self._wrap_method( self.update_insight_type_config, default_timeout=None, client_info=client_info, ), - self.list_recommenders: gapic_v1.method_async.wrap_method( + self.list_recommenders: self._wrap_method( self.list_recommenders, default_timeout=None, client_info=client_info, ), - self.list_insight_types: gapic_v1.method_async.wrap_method( + self.list_insight_types: self._wrap_method( self.list_insight_types, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("RecommenderGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest.py b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest.py index df0341a4f4c2..43ef2e70e500 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest.py @@ -16,26 +16,17 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.cloud.recommender_v1beta1.types import ( insight_type_config as gcr_insight_type_config, ) @@ -49,7 +40,13 @@ from google.cloud.recommender_v1beta1.types import recommender_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import RecommenderTransport +from .rest_base import _BaseRecommenderRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -536,8 +533,8 @@ class RecommenderRestStub: _interceptor: RecommenderRestInterceptor -class RecommenderRestTransport(RecommenderTransport): - """REST backend transport for Recommender. +class RecommenderRestTransport(_BaseRecommenderRestTransport): + """REST backend synchronous transport for Recommender. Provides insights and recommendations for cloud customers for various categories like performance optimization, cost savings, @@ -550,7 +547,6 @@ class RecommenderRestTransport(RecommenderTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -604,21 +600,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -629,19 +616,33 @@ def __init__( self._interceptor = interceptor or RecommenderRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetInsight(RecommenderRestStub): + class _GetInsight( + _BaseRecommenderRestTransport._BaseGetInsight, RecommenderRestStub + ): def __hash__(self): - return hash("GetInsight") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetInsight") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -671,50 +672,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=folders/*/locations/*/insightTypes/*/insights/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/insights/*}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_http_options() + ) request, metadata = self._interceptor.pre_get_insight(request, metadata) - pb_request = recommender_service.GetInsightRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRecommenderRestTransport._BaseGetInsight._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetInsight._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -730,19 +712,33 @@ def __call__( resp = self._interceptor.post_get_insight(resp) return resp - class _GetInsightTypeConfig(RecommenderRestStub): + class _GetInsightTypeConfig( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig, RecommenderRestStub + ): def __hash__(self): - return hash("GetInsightTypeConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetInsightTypeConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -768,44 +764,29 @@ def __call__( Configuration for an InsightType. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/config}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/config}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_insight_type_config( request, metadata ) - pb_request = recommender_service.GetInsightTypeConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetInsightTypeConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -821,19 +802,33 @@ def __call__( resp = self._interceptor.post_get_insight_type_config(resp) return resp - class _GetRecommendation(RecommenderRestStub): + class _GetRecommendation( + _BaseRecommenderRestTransport._BaseGetRecommendation, RecommenderRestStub + ): def __hash__(self): - return hash("GetRecommendation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetRecommendation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -863,52 +858,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetRecommendation._get_http_options() + ) request, metadata = self._interceptor.pre_get_recommendation( request, metadata ) - pb_request = recommender_service.GetRecommendationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetRecommendation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetRecommendation._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetRecommendation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -924,19 +896,33 @@ def __call__( resp = self._interceptor.post_get_recommendation(resp) return resp - class _GetRecommenderConfig(RecommenderRestStub): + class _GetRecommenderConfig( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig, RecommenderRestStub + ): def __hash__(self): - return hash("GetRecommenderConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.GetRecommenderConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -962,44 +948,29 @@ def __call__( Configuration for a Recommender. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/config}", - }, - { - "method": "get", - "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/config}", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_recommender_config( request, metadata ) - pb_request = recommender_service.GetRecommenderConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._GetRecommenderConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1015,19 +986,33 @@ def __call__( resp = self._interceptor.post_get_recommender_config(resp) return resp - class _ListInsights(RecommenderRestStub): + class _ListInsights( + _BaseRecommenderRestTransport._BaseListInsights, RecommenderRestStub + ): def __hash__(self): - return hash("ListInsights") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.ListInsights") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1053,50 +1038,31 @@ def __call__( Response to the ``ListInsights`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=billingAccounts/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=folders/*/locations/*/insightTypes/*}/insights", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=organizations/*/locations/*/insightTypes/*}/insights", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListInsights._get_http_options() + ) request, metadata = self._interceptor.pre_list_insights(request, metadata) - pb_request = recommender_service.ListInsightsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRecommenderRestTransport._BaseListInsights._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRecommenderRestTransport._BaseListInsights._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._ListInsights._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1112,9 +1078,33 @@ def __call__( resp = self._interceptor.post_list_insights(resp) return resp - class _ListInsightTypes(RecommenderRestStub): + class _ListInsightTypes( + _BaseRecommenderRestTransport._BaseListInsightTypes, RecommenderRestStub + ): def __hash__(self): - return hash("ListInsightTypes") + return hash("RecommenderRestTransport.ListInsightTypes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1140,39 +1130,29 @@ def __call__( Response for the ``ListInsightTypes`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/insightTypes", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListInsightTypes._get_http_options() + ) request, metadata = self._interceptor.pre_list_insight_types( request, metadata ) - pb_request = recommender_service.ListInsightTypesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseListInsightTypes._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseListInsightTypes._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = RecommenderRestTransport._ListInsightTypes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1188,19 +1168,33 @@ def __call__( resp = self._interceptor.post_list_insight_types(resp) return resp - class _ListRecommendations(RecommenderRestStub): + class _ListRecommendations( + _BaseRecommenderRestTransport._BaseListRecommendations, RecommenderRestStub + ): def __hash__(self): - return hash("ListRecommendations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.ListRecommendations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1226,52 +1220,29 @@ def __call__( Response to the ``ListRecommendations`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=billingAccounts/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=folders/*/locations/*/recommenders/*}/recommendations", - }, - { - "method": "get", - "uri": "/v1beta1/{parent=organizations/*/locations/*/recommenders/*}/recommendations", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListRecommendations._get_http_options() + ) request, metadata = self._interceptor.pre_list_recommendations( request, metadata ) - pb_request = recommender_service.ListRecommendationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseListRecommendations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseListRecommendations._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RecommenderRestTransport._ListRecommendations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1287,9 +1258,33 @@ def __call__( resp = self._interceptor.post_list_recommendations(resp) return resp - class _ListRecommenders(RecommenderRestStub): + class _ListRecommenders( + _BaseRecommenderRestTransport._BaseListRecommenders, RecommenderRestStub + ): def __hash__(self): - return hash("ListRecommenders") + return hash("RecommenderRestTransport.ListRecommenders") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1315,39 +1310,29 @@ def __call__( Response for the ``ListRecommender`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/recommenders", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseListRecommenders._get_http_options() + ) request, metadata = self._interceptor.pre_list_recommenders( request, metadata ) - pb_request = recommender_service.ListRecommendersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRecommenderRestTransport._BaseListRecommenders._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseListRecommenders._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = RecommenderRestTransport._ListRecommenders._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1363,19 +1348,34 @@ def __call__( resp = self._interceptor.post_list_recommenders(resp) return resp - class _MarkInsightAccepted(RecommenderRestStub): + class _MarkInsightAccepted( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted, RecommenderRestStub + ): def __hash__(self): - return hash("MarkInsightAccepted") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkInsightAccepted") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1405,62 +1405,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=folders/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/insights/*}:markAccepted", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_http_options() + ) request, metadata = self._interceptor.pre_mark_insight_accepted( request, metadata ) - pb_request = recommender_service.MarkInsightAcceptedRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._MarkInsightAccepted._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1476,19 +1448,35 @@ def __call__( resp = self._interceptor.post_mark_insight_accepted(resp) return resp - class _MarkRecommendationClaimed(RecommenderRestStub): + class _MarkRecommendationClaimed( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed, + RecommenderRestStub, + ): def __hash__(self): - return hash("MarkRecommendationClaimed") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationClaimed") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1519,64 +1507,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markClaimed", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_claimed( request, metadata ) - pb_request = recommender_service.MarkRecommendationClaimedRequest.pb( - request + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RecommenderRestTransport._MarkRecommendationClaimed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1592,19 +1552,34 @@ def __call__( resp = self._interceptor.post_mark_recommendation_claimed(resp) return resp - class _MarkRecommendationFailed(RecommenderRestStub): + class _MarkRecommendationFailed( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed, RecommenderRestStub + ): def __hash__(self): - return hash("MarkRecommendationFailed") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationFailed") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1635,62 +1610,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markFailed", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_failed( request, metadata ) - pb_request = recommender_service.MarkRecommendationFailedRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._MarkRecommendationFailed._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1706,19 +1653,35 @@ def __call__( resp = self._interceptor.post_mark_recommendation_failed(resp) return resp - class _MarkRecommendationSucceeded(RecommenderRestStub): + class _MarkRecommendationSucceeded( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded, + RecommenderRestStub, + ): def __hash__(self): - return hash("MarkRecommendationSucceeded") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.MarkRecommendationSucceeded") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1749,64 +1712,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - { - "method": "post", - "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", - "body": "*", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_http_options() + ) request, metadata = self._interceptor.pre_mark_recommendation_succeeded( request, metadata ) - pb_request = recommender_service.MarkRecommendationSucceededRequest.pb( - request + transcoded_request = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + RecommenderRestTransport._MarkRecommendationSucceeded._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1822,19 +1757,34 @@ def __call__( resp = self._interceptor.post_mark_recommendation_succeeded(resp) return resp - class _UpdateInsightTypeConfig(RecommenderRestStub): + class _UpdateInsightTypeConfig( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig, RecommenderRestStub + ): def __hash__(self): - return hash("UpdateInsightTypeConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.UpdateInsightTypeConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1861,52 +1811,34 @@ def __call__( Configuration for an InsightType. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}", - "body": "insight_type_config", - }, - { - "method": "post", - "uri": "/v1beta1/{insight_type_config.name=organizations/*/locations/*/insightTypes/*/config}", - "body": "insight_type_config", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_insight_type_config( request, metadata ) - pb_request = recommender_service.UpdateInsightTypeConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._UpdateInsightTypeConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1922,19 +1854,34 @@ def __call__( resp = self._interceptor.post_update_insight_type_config(resp) return resp - class _UpdateRecommenderConfig(RecommenderRestStub): + class _UpdateRecommenderConfig( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig, RecommenderRestStub + ): def __hash__(self): - return hash("UpdateRecommenderConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RecommenderRestTransport.UpdateRecommenderConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1960,52 +1907,34 @@ def __call__( Configuration for a Recommender. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{recommender_config.name=projects/*/locations/*/recommenders/*/config}", - "body": "recommender_config", - }, - { - "method": "post", - "uri": "/v1beta1/{recommender_config.name=organizations/*/locations/*/recommenders/*/config}", - "body": "recommender_config", - }, - ] + http_options = ( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_recommender_config( request, metadata ) - pb_request = recommender_service.UpdateRecommenderConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = RecommenderRestTransport._UpdateRecommenderConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest_base.py b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest_base.py new file mode 100644 index 000000000000..8c62f6d3f4ff --- /dev/null +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/services/recommender/transports/rest_base.py @@ -0,0 +1,919 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.recommender_v1beta1.types import ( + insight_type_config as gcr_insight_type_config, +) +from google.cloud.recommender_v1beta1.types import ( + recommender_config as gcr_recommender_config, +) +from google.cloud.recommender_v1beta1.types import insight +from google.cloud.recommender_v1beta1.types import insight_type_config +from google.cloud.recommender_v1beta1.types import recommendation +from google.cloud.recommender_v1beta1.types import recommender_config +from google.cloud.recommender_v1beta1.types import recommender_service + +from .base import DEFAULT_CLIENT_INFO, RecommenderTransport + + +class _BaseRecommenderRestTransport(RecommenderTransport): + """Base REST backend transport for Recommender. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "recommender.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'recommender.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetInsight: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=folders/*/locations/*/insightTypes/*/insights/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/insights/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetInsightRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetInsight._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInsightTypeConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/config}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/config}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetInsightTypeConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetInsightTypeConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRecommendation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetRecommendationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetRecommendation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRecommenderConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/config}", + }, + { + "method": "get", + "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/config}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.GetRecommenderConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseGetRecommenderConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInsights: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=billingAccounts/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=folders/*/locations/*/insightTypes/*}/insights", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=organizations/*/locations/*/insightTypes/*}/insights", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListInsightsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseListInsights._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInsightTypes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/insightTypes", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListInsightTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRecommendations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=billingAccounts/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=folders/*/locations/*/recommenders/*}/recommendations", + }, + { + "method": "get", + "uri": "/v1beta1/{parent=organizations/*/locations/*/recommenders/*}/recommendations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListRecommendationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseListRecommendations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRecommenders: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/recommenders", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.ListRecommendersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkInsightAccepted: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=folders/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=organizations/*/locations/*/insightTypes/*/insights/*}:markAccepted", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkInsightAcceptedRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkInsightAccepted._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationClaimed: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markClaimed", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationClaimedRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationClaimed._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationFailed: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markFailed", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationFailedRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationFailed._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMarkRecommendationSucceeded: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=billingAccounts/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=folders/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + { + "method": "post", + "uri": "/v1beta1/{name=organizations/*/locations/*/recommenders/*/recommendations/*}:markSucceeded", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.MarkRecommendationSucceededRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseMarkRecommendationSucceeded._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInsightTypeConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}", + "body": "insight_type_config", + }, + { + "method": "post", + "uri": "/v1beta1/{insight_type_config.name=organizations/*/locations/*/insightTypes/*/config}", + "body": "insight_type_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.UpdateInsightTypeConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseUpdateInsightTypeConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateRecommenderConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{recommender_config.name=projects/*/locations/*/recommenders/*/config}", + "body": "recommender_config", + }, + { + "method": "post", + "uri": "/v1beta1/{recommender_config.name=organizations/*/locations/*/recommenders/*/config}", + "body": "recommender_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = recommender_service.UpdateRecommenderConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRecommenderRestTransport._BaseUpdateRecommenderConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseRecommenderRestTransport",) diff --git a/packages/google-cloud-recommender/setup.py b/packages/google-cloud-recommender/setup.py index a444e48eba00..bdf342d5fef7 100644 --- a/packages/google-cloud-recommender/setup.py +++ b/packages/google-cloud-recommender/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py index b20b6b862d1c..288761f67a36 100644 --- a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py +++ b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,16 +53,8 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -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.recommender_v1.services.recommender import ( RecommenderAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.recommender_v1.types import recommender_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1130,25 +1153,6 @@ def test_list_insights(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_insights_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_insights), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_insights() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightsRequest() - - def test_list_insights_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1216,29 +1220,6 @@ def test_list_insights_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_insights_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_insights), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListInsightsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_insights() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightsRequest() - - @pytest.mark.asyncio async def test_list_insights_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1247,7 +1228,7 @@ async def test_list_insights_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1287,7 +1268,7 @@ async def test_list_insights_async( request_type=recommender_service.ListInsightsRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1353,7 +1334,7 @@ def test_list_insights_field_headers(): @pytest.mark.asyncio async def test_list_insights_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1423,7 +1404,7 @@ def test_list_insights_flattened_error(): @pytest.mark.asyncio async def test_list_insights_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1452,7 +1433,7 @@ async def test_list_insights_flattened_async(): @pytest.mark.asyncio async def test_list_insights_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1562,7 +1543,7 @@ def test_list_insights_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_insights_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1612,7 +1593,7 @@ async def test_list_insights_async_pager(): @pytest.mark.asyncio async def test_list_insights_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1706,25 +1687,6 @@ def test_get_insight(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_insight_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_insight), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_insight() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightRequest() - - def test_get_insight_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1788,35 +1750,6 @@ def test_get_insight_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_insight_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_insight), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - ) - response = await client.get_insight() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightRequest() - - @pytest.mark.asyncio async def test_get_insight_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1825,7 +1758,7 @@ async def test_get_insight_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1864,7 +1797,7 @@ async def test_get_insight_async( transport: str = "grpc_asyncio", request_type=recommender_service.GetInsightRequest ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1942,7 +1875,7 @@ def test_get_insight_field_headers(): @pytest.mark.asyncio async def test_get_insight_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2010,7 +1943,7 @@ def test_get_insight_flattened_error(): @pytest.mark.asyncio async def test_get_insight_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2037,7 +1970,7 @@ async def test_get_insight_flattened_async(): @pytest.mark.asyncio async def test_get_insight_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2099,27 +2032,6 @@ def test_mark_insight_accepted(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_mark_insight_accepted_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_insight_accepted), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_insight_accepted() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkInsightAcceptedRequest() - - def test_mark_insight_accepted_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2192,37 +2104,6 @@ def test_mark_insight_accepted_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_insight_accepted_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_insight_accepted), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - ) - response = await client.mark_insight_accepted() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkInsightAcceptedRequest() - - @pytest.mark.asyncio async def test_mark_insight_accepted_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2231,7 +2112,7 @@ async def test_mark_insight_accepted_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2271,7 +2152,7 @@ async def test_mark_insight_accepted_async( request_type=recommender_service.MarkInsightAcceptedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2353,7 +2234,7 @@ def test_mark_insight_accepted_field_headers(): @pytest.mark.asyncio async def test_mark_insight_accepted_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2435,7 +2316,7 @@ def test_mark_insight_accepted_flattened_error(): @pytest.mark.asyncio async def test_mark_insight_accepted_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2472,7 +2353,7 @@ async def test_mark_insight_accepted_flattened_async(): @pytest.mark.asyncio async def test_mark_insight_accepted_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2524,27 +2405,6 @@ def test_list_recommendations(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_recommendations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommendations), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_recommendations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendationsRequest() - - def test_list_recommendations_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2618,31 +2478,6 @@ def test_list_recommendations_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_recommendations_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommendations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListRecommendationsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_recommendations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendationsRequest() - - @pytest.mark.asyncio async def test_list_recommendations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2651,7 +2486,7 @@ async def test_list_recommendations_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2691,7 +2526,7 @@ async def test_list_recommendations_async( request_type=recommender_service.ListRecommendationsRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2761,7 +2596,7 @@ def test_list_recommendations_field_headers(): @pytest.mark.asyncio async def test_list_recommendations_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2840,7 +2675,7 @@ def test_list_recommendations_flattened_error(): @pytest.mark.asyncio async def test_list_recommendations_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2875,7 +2710,7 @@ async def test_list_recommendations_flattened_async(): @pytest.mark.asyncio async def test_list_recommendations_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2990,7 +2825,7 @@ def test_list_recommendations_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_recommendations_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3042,7 +2877,7 @@ async def test_list_recommendations_async_pager(): @pytest.mark.asyncio async def test_list_recommendations_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3138,27 +2973,6 @@ def test_get_recommendation(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_get_recommendation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommendation), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_recommendation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommendationRequest() - - def test_get_recommendation_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3228,36 +3042,6 @@ def test_get_recommendation_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_recommendation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommendation), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.get_recommendation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommendationRequest() - - @pytest.mark.asyncio async def test_get_recommendation_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3266,7 +3050,7 @@ async def test_get_recommendation_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3306,7 +3090,7 @@ async def test_get_recommendation_async( request_type=recommender_service.GetRecommendationRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3386,7 +3170,7 @@ def test_get_recommendation_field_headers(): @pytest.mark.asyncio async def test_get_recommendation_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3460,7 +3244,7 @@ def test_get_recommendation_flattened_error(): @pytest.mark.asyncio async def test_get_recommendation_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3491,7 +3275,7 @@ async def test_get_recommendation_flattened_async(): @pytest.mark.asyncio async def test_get_recommendation_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3551,14 +3335,22 @@ def test_mark_recommendation_dismissed(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_dismissed_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_dismissed_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = recommender_service.MarkRecommendationDismissedRequest( + name="name_value", + etag="etag_value", + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.mark_recommendation_dismissed), "__call__" @@ -3566,36 +3358,7 @@ def test_mark_recommendation_dismissed_empty_call(): call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mark_recommendation_dismissed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationDismissedRequest() - - -def test_mark_recommendation_dismissed_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = recommender_service.MarkRecommendationDismissedRequest( - name="name_value", - etag="etag_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_dismissed), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_dismissed(request=request) + client.mark_recommendation_dismissed(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == recommender_service.MarkRecommendationDismissedRequest( @@ -3644,36 +3407,6 @@ def test_mark_recommendation_dismissed_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_dismissed_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_dismissed), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_dismissed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationDismissedRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_dismissed_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3682,7 +3415,7 @@ async def test_mark_recommendation_dismissed_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3722,7 +3455,7 @@ async def test_mark_recommendation_dismissed_async( request_type=recommender_service.MarkRecommendationDismissedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3802,7 +3535,7 @@ def test_mark_recommendation_dismissed_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_dismissed_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3881,27 +3614,6 @@ def test_mark_recommendation_claimed(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_claimed_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_claimed), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_claimed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationClaimedRequest() - - def test_mark_recommendation_claimed_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3974,36 +3686,6 @@ def test_mark_recommendation_claimed_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_claimed_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_claimed), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_claimed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationClaimedRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_claimed_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4012,7 +3694,7 @@ async def test_mark_recommendation_claimed_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4052,7 +3734,7 @@ async def test_mark_recommendation_claimed_async( request_type=recommender_service.MarkRecommendationClaimedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4132,7 +3814,7 @@ def test_mark_recommendation_claimed_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4216,7 +3898,7 @@ def test_mark_recommendation_claimed_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4255,7 +3937,7 @@ async def test_mark_recommendation_claimed_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4317,27 +3999,6 @@ def test_mark_recommendation_succeeded(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_succeeded_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_succeeded), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_succeeded() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationSucceededRequest() - - def test_mark_recommendation_succeeded_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4410,36 +4071,6 @@ def test_mark_recommendation_succeeded_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_succeeded_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_succeeded), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_succeeded() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationSucceededRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_succeeded_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4448,7 +4079,7 @@ async def test_mark_recommendation_succeeded_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4488,7 +4119,7 @@ async def test_mark_recommendation_succeeded_async( request_type=recommender_service.MarkRecommendationSucceededRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4568,7 +4199,7 @@ def test_mark_recommendation_succeeded_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4652,7 +4283,7 @@ def test_mark_recommendation_succeeded_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4691,7 +4322,7 @@ async def test_mark_recommendation_succeeded_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4753,27 +4384,6 @@ def test_mark_recommendation_failed(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_failed_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_failed), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_failed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationFailedRequest() - - def test_mark_recommendation_failed_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4846,36 +4456,6 @@ def test_mark_recommendation_failed_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_failed_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_failed), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_failed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationFailedRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_failed_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4884,7 +4464,7 @@ async def test_mark_recommendation_failed_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4924,7 +4504,7 @@ async def test_mark_recommendation_failed_async( request_type=recommender_service.MarkRecommendationFailedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5004,7 +4584,7 @@ def test_mark_recommendation_failed_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_failed_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5088,7 +4668,7 @@ def test_mark_recommendation_failed_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_failed_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5127,7 +4707,7 @@ async def test_mark_recommendation_failed_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_failed_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5185,27 +4765,6 @@ def test_get_recommender_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_get_recommender_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommender_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommenderConfigRequest() - - def test_get_recommender_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5276,34 +4835,6 @@ def test_get_recommender_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_recommender_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommender_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.get_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommenderConfigRequest() - - @pytest.mark.asyncio async def test_get_recommender_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5312,7 +4843,7 @@ async def test_get_recommender_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5352,7 +4883,7 @@ async def test_get_recommender_config_async( request_type=recommender_service.GetRecommenderConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5428,7 +4959,7 @@ def test_get_recommender_config_field_headers(): @pytest.mark.asyncio async def test_get_recommender_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5502,7 +5033,7 @@ def test_get_recommender_config_flattened_error(): @pytest.mark.asyncio async def test_get_recommender_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5533,7 +5064,7 @@ async def test_get_recommender_config_flattened_async(): @pytest.mark.asyncio async def test_get_recommender_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5589,27 +5120,6 @@ def test_update_recommender_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_recommender_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_recommender_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateRecommenderConfigRequest() - - def test_update_recommender_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5676,34 +5186,6 @@ def test_update_recommender_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_recommender_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_recommender_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.update_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateRecommenderConfigRequest() - - @pytest.mark.asyncio async def test_update_recommender_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5712,7 +5194,7 @@ async def test_update_recommender_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5752,7 +5234,7 @@ async def test_update_recommender_config_async( request_type=recommender_service.UpdateRecommenderConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5828,7 +5310,7 @@ def test_update_recommender_config_field_headers(): @pytest.mark.asyncio async def test_update_recommender_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5911,7 +5393,7 @@ def test_update_recommender_config_flattened_error(): @pytest.mark.asyncio async def test_update_recommender_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5948,7 +5430,7 @@ async def test_update_recommender_config_flattened_async(): @pytest.mark.asyncio async def test_update_recommender_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6007,27 +5489,6 @@ def test_get_insight_type_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_get_insight_type_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_insight_type_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightTypeConfigRequest() - - def test_get_insight_type_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6098,34 +5559,6 @@ def test_get_insight_type_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_insight_type_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_insight_type_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.get_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightTypeConfigRequest() - - @pytest.mark.asyncio async def test_get_insight_type_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6134,7 +5567,7 @@ async def test_get_insight_type_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6174,7 +5607,7 @@ async def test_get_insight_type_config_async( request_type=recommender_service.GetInsightTypeConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6250,7 +5683,7 @@ def test_get_insight_type_config_field_headers(): @pytest.mark.asyncio async def test_get_insight_type_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6324,7 +5757,7 @@ def test_get_insight_type_config_flattened_error(): @pytest.mark.asyncio async def test_get_insight_type_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6355,7 +5788,7 @@ async def test_get_insight_type_config_flattened_async(): @pytest.mark.asyncio async def test_get_insight_type_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6411,27 +5844,6 @@ def test_update_insight_type_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_insight_type_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_insight_type_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateInsightTypeConfigRequest() - - def test_update_insight_type_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6498,34 +5910,6 @@ def test_update_insight_type_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_insight_type_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_insight_type_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.update_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateInsightTypeConfigRequest() - - @pytest.mark.asyncio async def test_update_insight_type_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6534,7 +5918,7 @@ async def test_update_insight_type_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6574,7 +5958,7 @@ async def test_update_insight_type_config_async( request_type=recommender_service.UpdateInsightTypeConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6650,7 +6034,7 @@ def test_update_insight_type_config_field_headers(): @pytest.mark.asyncio async def test_update_insight_type_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6733,7 +6117,7 @@ def test_update_insight_type_config_flattened_error(): @pytest.mark.asyncio async def test_update_insight_type_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6770,7 +6154,7 @@ async def test_update_insight_type_config_flattened_async(): @pytest.mark.asyncio async def test_update_insight_type_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6785,46 +6169,6 @@ async def test_update_insight_type_config_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.ListInsightsRequest, - dict, - ], -) -def test_list_insights_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = recommender_service.ListInsightsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_service.ListInsightsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_insights(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInsightsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_insights_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6961,87 +6305,6 @@ def test_list_insights_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_insights_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_insights" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_list_insights" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.ListInsightsRequest.pb( - recommender_service.ListInsightsRequest() - ) - 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 = recommender_service.ListInsightsResponse.to_json( - recommender_service.ListInsightsResponse() - ) - - request = recommender_service.ListInsightsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_service.ListInsightsResponse() - - client.list_insights( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_insights_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListInsightsRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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.list_insights(request) - - def test_list_insights_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7166,68 +6429,14 @@ def test_list_insights_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetInsightRequest, - dict, - ], -) -def test_get_insight_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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 = insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight.Insight.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_insight(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight.Insight) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.target_resources == ["target_resources_value"] - assert response.insight_subtype == "insight_subtype_value" - assert response.category == insight.Insight.Category.COST - assert response.severity == insight.Insight.Severity.LOW - assert response.etag == "etag_value" - - -def test_get_insight_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_insight_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -7339,87 +6548,6 @@ def test_get_insight_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_insight_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_insight" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetInsightRequest.pb( - recommender_service.GetInsightRequest() - ) - 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 = insight.Insight.to_json(insight.Insight()) - - request = recommender_service.GetInsightRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight.Insight() - - client.get_insight( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_insight_rest_bad_request( - transport: str = "rest", request_type=recommender_service.GetInsightRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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_insight(request) - - def test_get_insight_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7479,66 +6607,6 @@ def test_get_insight_rest_flattened_error(transport: str = "rest"): ) -def test_get_insight_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkInsightAcceptedRequest, - dict, - ], -) -def test_mark_insight_accepted_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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 = insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight.Insight.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_insight_accepted(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight.Insight) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.target_resources == ["target_resources_value"] - assert response.insight_subtype == "insight_subtype_value" - assert response.category == insight.Insight.Category.COST - assert response.severity == insight.Insight.Severity.LOW - assert response.etag == "etag_value" - - def test_mark_insight_accepted_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7676,87 +6744,6 @@ def test_mark_insight_accepted_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_insight_accepted_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_insight_accepted" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_insight_accepted" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkInsightAcceptedRequest.pb( - recommender_service.MarkInsightAcceptedRequest() - ) - 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 = insight.Insight.to_json(insight.Insight()) - - request = recommender_service.MarkInsightAcceptedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight.Insight() - - client.mark_insight_accepted( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_insight_accepted_rest_bad_request( - transport: str = "rest", request_type=recommender_service.MarkInsightAcceptedRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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.mark_insight_accepted(request) - - def test_mark_insight_accepted_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7820,52 +6807,6 @@ def test_mark_insight_accepted_rest_flattened_error(transport: str = "rest"): ) -def test_mark_insight_accepted_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.ListRecommendationsRequest, - dict, - ], -) -def test_list_recommendations_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = recommender_service.ListRecommendationsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_service.ListRecommendationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_recommendations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRecommendationsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_recommendations_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8008,89 +6949,6 @@ def test_list_recommendations_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_recommendations_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_recommendations" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_list_recommendations" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.ListRecommendationsRequest.pb( - recommender_service.ListRecommendationsRequest() - ) - 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 = ( - recommender_service.ListRecommendationsResponse.to_json( - recommender_service.ListRecommendationsResponse() - ) - ) - - request = recommender_service.ListRecommendationsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_service.ListRecommendationsResponse() - - client.list_recommendations( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_recommendations_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListRecommendationsRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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.list_recommendations(request) - - def test_list_recommendations_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8217,58 +7075,6 @@ def test_list_recommendations_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetRecommendationRequest, - dict, - ], -) -def test_get_recommendation_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_recommendation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_get_recommendation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8392,89 +7198,6 @@ def test_get_recommendation_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recommendation_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommendation" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_recommendation" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetRecommendationRequest.pb( - recommender_service.GetRecommendationRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.GetRecommendationRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.get_recommendation( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_recommendation_rest_bad_request( - transport: str = "rest", request_type=recommender_service.GetRecommendationRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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_recommendation(request) - - def test_get_recommendation_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8534,64 +7257,6 @@ def test_get_recommendation_rest_flattened_error(transport: str = "rest"): ) -def test_get_recommendation_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationDismissedRequest, - dict, - ], -) -def test_mark_recommendation_dismissed_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_dismissed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_dismissed_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8719,148 +7384,6 @@ def test_mark_recommendation_dismissed_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_dismissed_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_dismissed" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_dismissed" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationDismissedRequest.pb( - recommender_service.MarkRecommendationDismissedRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationDismissedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_dismissed( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_dismissed_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationDismissedRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_dismissed(request) - - -def test_mark_recommendation_dismissed_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationClaimedRequest, - dict, - ], -) -def test_mark_recommendation_claimed_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_claimed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_claimed_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8998,124 +7521,40 @@ def test_mark_recommendation_claimed_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_claimed_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_mark_recommendation_claimed_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), + transport="rest", ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_claimed" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_claimed" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationClaimedRequest.pb( - recommender_service.MarkRecommendationClaimedRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) + # 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 = recommendation.Recommendation() - request = recommender_service.MarkRecommendationClaimedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } - client.mark_recommendation_claimed( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + state_metadata={"key_value": "value_value"}, + etag="etag_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_mark_recommendation_claimed_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationClaimedRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_claimed(request) - - -def test_mark_recommendation_claimed_rest_flattened(): - client = RecommenderClient( - 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 = recommendation.Recommendation() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - state_metadata={"key_value": "value_value"}, - etag="etag_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.mark_recommendation_claimed(**mock_args) + client.mark_recommendation_claimed(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -9145,64 +7584,6 @@ def test_mark_recommendation_claimed_rest_flattened_error(transport: str = "rest ) -def test_mark_recommendation_claimed_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationSucceededRequest, - dict, - ], -) -def test_mark_recommendation_succeeded_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_succeeded(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_succeeded_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9342,90 +7723,6 @@ def test_mark_recommendation_succeeded_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_succeeded_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_succeeded" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_succeeded" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationSucceededRequest.pb( - recommender_service.MarkRecommendationSucceededRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationSucceededRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_succeeded( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_succeeded_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationSucceededRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_succeeded(request) - - def test_mark_recommendation_succeeded_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9489,64 +7786,6 @@ def test_mark_recommendation_succeeded_rest_flattened_error(transport: str = "re ) -def test_mark_recommendation_succeeded_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationFailedRequest, - dict, - ], -) -def test_mark_recommendation_failed_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_failed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_failed_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9684,92 +7923,8 @@ def test_mark_recommendation_failed_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_failed_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_failed" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_failed" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationFailedRequest.pb( - recommender_service.MarkRecommendationFailedRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationFailedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_failed( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_failed_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationFailedRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_failed(request) - - -def test_mark_recommendation_failed_rest_flattened(): - client = RecommenderClient( +def test_mark_recommendation_failed_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -9831,60 +7986,6 @@ def test_mark_recommendation_failed_rest_flattened_error(transport: str = "rest" ) -def test_mark_recommendation_failed_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetRecommenderConfigRequest, - dict, - ], -) -def test_get_recommender_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - 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 = recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_config.RecommenderConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_recommender_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommender_config.RecommenderConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - def test_get_recommender_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10009,90 +8110,6 @@ def test_get_recommender_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recommender_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommender_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_recommender_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetRecommenderConfigRequest.pb( - recommender_service.GetRecommenderConfigRequest() - ) - 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 = recommender_config.RecommenderConfig.to_json( - recommender_config.RecommenderConfig() - ) - - request = recommender_service.GetRecommenderConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_config.RecommenderConfig() - - client.get_recommender_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_recommender_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.GetRecommenderConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - 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_recommender_config(request) - - def test_get_recommender_config_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10152,158 +8169,24 @@ def test_get_recommender_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_recommender_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_update_recommender_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.UpdateRecommenderConfigRequest, - dict, - ], -) -def test_update_recommender_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = { - "recommender_config": { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - } - request_init["recommender_config"] = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config", - "recommender_generation_config": {"params": {"fields": {}}}, - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "revision_id": "revision_id_value", - "annotations": {}, - "display_name": "display_name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = recommender_service.UpdateRecommenderConfigRequest.meta.fields[ - "recommender_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["recommender_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["recommender_config"][field])): - del request_init["recommender_config"][field][i][subfield] - else: - del request_init["recommender_config"][field][subfield] - 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 = gcr_recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_recommender_config.RecommenderConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_recommender_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_recommender_config.RecommenderConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - -def test_update_recommender_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_recommender_config - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_recommender_config + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -10421,92 +8304,6 @@ def test_update_recommender_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_recommender_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_recommender_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_update_recommender_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.UpdateRecommenderConfigRequest.pb( - recommender_service.UpdateRecommenderConfigRequest() - ) - 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 = gcr_recommender_config.RecommenderConfig.to_json( - gcr_recommender_config.RecommenderConfig() - ) - - request = recommender_service.UpdateRecommenderConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_recommender_config.RecommenderConfig() - - client.update_recommender_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_recommender_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.UpdateRecommenderConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "recommender_config": { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - } - 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_recommender_config(request) - - def test_update_recommender_config_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10574,60 +8371,6 @@ def test_update_recommender_config_rest_flattened_error(transport: str = "rest") ) -def test_update_recommender_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetInsightTypeConfigRequest, - dict, - ], -) -def test_get_insight_type_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - 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 = insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight_type_config.InsightTypeConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_insight_type_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight_type_config.InsightTypeConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - def test_get_insight_type_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10752,92 +8495,8 @@ def test_get_insight_type_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_insight_type_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight_type_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_insight_type_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetInsightTypeConfigRequest.pb( - recommender_service.GetInsightTypeConfigRequest() - ) - 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 = insight_type_config.InsightTypeConfig.to_json( - insight_type_config.InsightTypeConfig() - ) - - request = recommender_service.GetInsightTypeConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight_type_config.InsightTypeConfig() - - client.get_insight_type_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_insight_type_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.GetInsightTypeConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - 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_insight_type_config(request) - - -def test_get_insight_type_config_rest_flattened(): - client = RecommenderClient( +def test_get_insight_type_config_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -10895,140 +8554,6 @@ def test_get_insight_type_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_insight_type_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.UpdateInsightTypeConfigRequest, - dict, - ], -) -def test_update_insight_type_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "insight_type_config": { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - } - request_init["insight_type_config"] = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config", - "insight_type_generation_config": {"params": {"fields": {}}}, - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "revision_id": "revision_id_value", - "annotations": {}, - "display_name": "display_name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = recommender_service.UpdateInsightTypeConfigRequest.meta.fields[ - "insight_type_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["insight_type_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["insight_type_config"][field])): - del request_init["insight_type_config"][field][i][subfield] - else: - del request_init["insight_type_config"][field][subfield] - 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 = gcr_insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_insight_type_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_insight_type_config.InsightTypeConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - def test_update_insight_type_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11164,42 +8689,2771 @@ def test_update_insight_type_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_insight_type_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_update_insight_type_config_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), + transport="rest", ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_insight_type_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_update_insight_type_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.UpdateInsightTypeConfigRequest.pb( - recommender_service.UpdateInsightTypeConfigRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = gcr_insight_type_config.InsightTypeConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "insight_type_config": { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_insight_type_config.InsightTypeConfig.to_json( - gcr_insight_type_config.InsightTypeConfig() + # get truthy value for each flattened field + mock_args = dict( + insight_type_config=gcr_insight_type_config.InsightTypeConfig( + 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 + # Convert return value to protobuf type + return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_insight_type_config(**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/v1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}" + % client.transport._host, + args[1], + ) + + +def test_update_insight_type_config_rest_flattened_error(transport: str = "rest"): + client = RecommenderClient( + 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_insight_type_config( + recommender_service.UpdateInsightTypeConfigRequest(), + insight_type_config=gcr_insight_type_config.InsightTypeConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommenderClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommenderClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RecommenderClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommenderGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RecommenderGrpcTransport, + transports.RecommenderGrpcAsyncIOTransport, + transports.RecommenderRestTransport, + ], +) +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_transport_kind_grpc(): + transport = RecommenderClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insights_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = recommender_service.ListInsightsResponse() + client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = insight.Insight() + client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_insight_accepted_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = insight.Insight() + client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommendations_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = recommender_service.ListRecommendationsResponse() + client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommendation_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.get_recommendation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_dismissed_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_dismissed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_dismissed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationDismissedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_claimed_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_claimed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_succeeded_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_succeeded(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_failed_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_failed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommender_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + call.return_value = recommender_config.RecommenderConfig() + client.get_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_recommender_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + call.return_value = gcr_recommender_config.RecommenderConfig() + client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_type_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + call.return_value = insight_type_config.InsightTypeConfig() + client.get_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_insight_type_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + call.return_value = gcr_insight_type_config.InsightTypeConfig() + client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RecommenderAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_insights_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_insight_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + ) + await client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_insight_accepted_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + ) + await client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_recommendations_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recommendation_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.get_recommendation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_dismissed_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_dismissed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_dismissed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationDismissedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_claimed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_succeeded(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_failed_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_failed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recommender_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.get_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_recommender_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_insight_type_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.get_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_insight_type_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RecommenderClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_insights_rest_bad_request( + request_type=recommender_service.ListInsightsRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_insights(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.ListInsightsRequest, + dict, + ], +) +def test_list_insights_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_service.ListInsightsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_insights(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInsightsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_insights_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_insights" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_list_insights" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.ListInsightsRequest.pb( + recommender_service.ListInsightsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_service.ListInsightsResponse.to_json( + recommender_service.ListInsightsResponse() + ) + req.return_value.content = return_value + + request = recommender_service.ListInsightsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_service.ListInsightsResponse() + + client.list_insights( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_insight_rest_bad_request( + request_type=recommender_service.GetInsightRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_insight(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetInsightRequest, + dict, + ], +) +def test_get_insight_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight.Insight.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_insight(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.target_resources == ["target_resources_value"] + assert response.insight_subtype == "insight_subtype_value" + assert response.category == insight.Insight.Category.COST + assert response.severity == insight.Insight.Severity.LOW + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_insight_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_insight" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetInsightRequest.pb( + recommender_service.GetInsightRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight.Insight.to_json(insight.Insight()) + req.return_value.content = return_value + + request = recommender_service.GetInsightRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight.Insight() + + client.get_insight( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_insight_accepted_rest_bad_request( + request_type=recommender_service.MarkInsightAcceptedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_insight_accepted(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkInsightAcceptedRequest, + dict, + ], +) +def test_mark_insight_accepted_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight.Insight.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_insight_accepted(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.target_resources == ["target_resources_value"] + assert response.insight_subtype == "insight_subtype_value" + assert response.category == insight.Insight.Category.COST + assert response.severity == insight.Insight.Severity.LOW + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_insight_accepted_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_insight_accepted" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_insight_accepted" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkInsightAcceptedRequest.pb( + recommender_service.MarkInsightAcceptedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight.Insight.to_json(insight.Insight()) + req.return_value.content = return_value + + request = recommender_service.MarkInsightAcceptedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight.Insight() + + client.mark_insight_accepted( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_recommendations_rest_bad_request( + request_type=recommender_service.ListRecommendationsRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_recommendations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.ListRecommendationsRequest, + dict, + ], +) +def test_list_recommendations_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_service.ListRecommendationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_recommendations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecommendationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_recommendations_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_recommendations" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_list_recommendations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.ListRecommendationsRequest.pb( + recommender_service.ListRecommendationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_service.ListRecommendationsResponse.to_json( + recommender_service.ListRecommendationsResponse() + ) + req.return_value.content = return_value + + request = recommender_service.ListRecommendationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_service.ListRecommendationsResponse() + + client.list_recommendations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_recommendation_rest_bad_request( + request_type=recommender_service.GetRecommendationRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_recommendation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetRecommendationRequest, + dict, + ], +) +def test_get_recommendation_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_recommendation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_recommendation_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommendation" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_recommendation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetRecommendationRequest.pb( + recommender_service.GetRecommendationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.GetRecommendationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.get_recommendation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_dismissed_rest_bad_request( + request_type=recommender_service.MarkRecommendationDismissedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_dismissed(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationDismissedRequest, + dict, + ], +) +def test_mark_recommendation_dismissed_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_dismissed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_dismissed_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_dismissed" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_dismissed" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationDismissedRequest.pb( + recommender_service.MarkRecommendationDismissedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationDismissedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_dismissed( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_claimed_rest_bad_request( + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_claimed(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationClaimedRequest, + dict, + ], +) +def test_mark_recommendation_claimed_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_claimed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_claimed_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_claimed" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_claimed" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationClaimedRequest.pb( + recommender_service.MarkRecommendationClaimedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationClaimedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_claimed( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_succeeded_rest_bad_request( + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_succeeded(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationSucceededRequest, + dict, + ], +) +def test_mark_recommendation_succeeded_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_succeeded(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_succeeded_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_succeeded" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_succeeded" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationSucceededRequest.pb( + recommender_service.MarkRecommendationSucceededRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationSucceededRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_succeeded( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_failed_rest_bad_request( + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_failed(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationFailedRequest, + dict, + ], +) +def test_mark_recommendation_failed_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_failed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_failed_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_failed" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_failed" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationFailedRequest.pb( + recommender_service.MarkRecommendationFailedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationFailedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_failed( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_recommender_config_rest_bad_request( + request_type=recommender_service.GetRecommenderConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_recommender_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetRecommenderConfigRequest, + dict, + ], +) +def test_get_recommender_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + 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 = recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_config.RecommenderConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_recommender_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommender_config.RecommenderConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_recommender_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommender_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_recommender_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetRecommenderConfigRequest.pb( + recommender_service.GetRecommenderConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_config.RecommenderConfig.to_json( + recommender_config.RecommenderConfig() + ) + req.return_value.content = return_value + + request = recommender_service.GetRecommenderConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_config.RecommenderConfig() + + client.get_recommender_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_recommender_config_rest_bad_request( + request_type=recommender_service.UpdateRecommenderConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "recommender_config": { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_recommender_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.UpdateRecommenderConfigRequest, + dict, + ], +) +def test_update_recommender_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "recommender_config": { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + } + request_init["recommender_config"] = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config", + "recommender_generation_config": {"params": {"fields": {}}}, + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "revision_id": "revision_id_value", + "annotations": {}, + "display_name": "display_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = recommender_service.UpdateRecommenderConfigRequest.meta.fields[ + "recommender_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["recommender_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["recommender_config"][field])): + del request_init["recommender_config"][field][i][subfield] + else: + del request_init["recommender_config"][field][subfield] + 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 = gcr_recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_recommender_config.RecommenderConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_recommender_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_recommender_config.RecommenderConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_recommender_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_recommender_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_update_recommender_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.UpdateRecommenderConfigRequest.pb( + recommender_service.UpdateRecommenderConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_recommender_config.RecommenderConfig.to_json( + gcr_recommender_config.RecommenderConfig() + ) + req.return_value.content = return_value + + request = recommender_service.UpdateRecommenderConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_recommender_config.RecommenderConfig() + + client.update_recommender_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_insight_type_config_rest_bad_request( + request_type=recommender_service.GetInsightTypeConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_insight_type_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetInsightTypeConfigRequest, + dict, + ], +) +def test_get_insight_type_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + 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 = insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight_type_config.InsightTypeConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_insight_type_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight_type_config.InsightTypeConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_insight_type_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight_type_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_insight_type_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetInsightTypeConfigRequest.pb( + recommender_service.GetInsightTypeConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight_type_config.InsightTypeConfig.to_json( + insight_type_config.InsightTypeConfig() + ) + req.return_value.content = return_value + + request = recommender_service.GetInsightTypeConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight_type_config.InsightTypeConfig() + + client.get_insight_type_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_insight_type_config_rest_bad_request( + request_type=recommender_service.UpdateInsightTypeConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "insight_type_config": { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_insight_type_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.UpdateInsightTypeConfigRequest, + dict, + ], +) +def test_update_insight_type_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "insight_type_config": { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + } + request_init["insight_type_config"] = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config", + "insight_type_generation_config": {"params": {"fields": {}}}, + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "revision_id": "revision_id_value", + "annotations": {}, + "display_name": "display_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = recommender_service.UpdateInsightTypeConfigRequest.meta.fields[ + "insight_type_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["insight_type_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["insight_type_config"][field])): + del request_init["insight_type_config"][field][i][subfield] + else: + del request_init["insight_type_config"][field][subfield] + 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 = gcr_insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_insight_type_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_insight_type_config.InsightTypeConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_insight_type_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_insight_type_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_update_insight_type_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.UpdateInsightTypeConfigRequest.pb( + recommender_service.UpdateInsightTypeConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_insight_type_config.InsightTypeConfig.to_json( + gcr_insight_type_config.InsightTypeConfig() + ) + req.return_value.content = return_value request = recommender_service.UpdateInsightTypeConfigRequest() metadata = [ @@ -11217,216 +11471,297 @@ def test_update_insight_type_config_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insights_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_insight_accepted_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommendations_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + assert args[0] == request_msg -def test_update_insight_type_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.UpdateInsightTypeConfigRequest, -): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommendation_empty_call_rest(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "insight_type_config": { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - } - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + client.get_recommendation(request=None) - # 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_insight_type_config(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + assert args[0] == request_msg -def test_update_insight_type_config_rest_flattened(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_dismissed_empty_call_rest(): client = RecommenderClient( 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 = gcr_insight_type_config.InsightTypeConfig() + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_dismissed), "__call__" + ) as call: + client.mark_recommendation_dismissed(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "insight_type_config": { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationDismissedRequest() - # get truthy value for each flattened field - mock_args = dict( - insight_type_config=gcr_insight_type_config.InsightTypeConfig( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.update_insight_type_config(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_claimed_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v1/{insight_type_config.name=projects/*/locations/*/insightTypes/*/config}" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + client.mark_recommendation_claimed(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() -def test_update_insight_type_config_rest_flattened_error(transport: str = "rest"): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_succeeded_empty_call_rest(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_insight_type_config( - recommender_service.UpdateInsightTypeConfigRequest(), - insight_type_config=gcr_insight_type_config.InsightTypeConfig( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + client.mark_recommendation_succeeded(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() -def test_update_insight_type_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RecommenderGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_failed_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.RecommenderGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommenderClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + client.mark_recommendation_failed(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.RecommenderGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommenderClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommenderClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.RecommenderGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommender_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = RecommenderClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + client.get_recommender_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommenderGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RecommenderClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommenderGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_recommender_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.RecommenderGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_type_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + client.get_insight_type_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.RecommenderGrpcTransport, - transports.RecommenderGrpcAsyncIOTransport, - transports.RecommenderRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = RecommenderClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_insight_type_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -12183,36 +12518,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1beta1/test_recommender.py b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1beta1/test_recommender.py index 4ca53c9d5518..9705dc851d87 100644 --- a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1beta1/test_recommender.py +++ b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1beta1/test_recommender.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,16 +53,8 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -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.recommender_v1beta1.services.recommender import ( RecommenderAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.recommender_v1beta1.types import recommender_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1130,25 +1153,6 @@ def test_list_insights(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_insights_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_insights), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_insights() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightsRequest() - - def test_list_insights_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1216,29 +1220,6 @@ def test_list_insights_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_insights_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_insights), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListInsightsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_insights() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightsRequest() - - @pytest.mark.asyncio async def test_list_insights_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1247,7 +1228,7 @@ async def test_list_insights_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1287,7 +1268,7 @@ async def test_list_insights_async( request_type=recommender_service.ListInsightsRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1353,7 +1334,7 @@ def test_list_insights_field_headers(): @pytest.mark.asyncio async def test_list_insights_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1423,7 +1404,7 @@ def test_list_insights_flattened_error(): @pytest.mark.asyncio async def test_list_insights_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1452,7 +1433,7 @@ async def test_list_insights_flattened_async(): @pytest.mark.asyncio async def test_list_insights_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1562,7 +1543,7 @@ def test_list_insights_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_insights_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1612,7 +1593,7 @@ async def test_list_insights_async_pager(): @pytest.mark.asyncio async def test_list_insights_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1706,25 +1687,6 @@ def test_get_insight(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_insight_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_insight), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_insight() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightRequest() - - def test_get_insight_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1788,35 +1750,6 @@ def test_get_insight_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_insight_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_insight), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - ) - response = await client.get_insight() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightRequest() - - @pytest.mark.asyncio async def test_get_insight_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1825,7 +1758,7 @@ async def test_get_insight_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1864,7 +1797,7 @@ async def test_get_insight_async( transport: str = "grpc_asyncio", request_type=recommender_service.GetInsightRequest ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1942,7 +1875,7 @@ def test_get_insight_field_headers(): @pytest.mark.asyncio async def test_get_insight_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2010,7 +1943,7 @@ def test_get_insight_flattened_error(): @pytest.mark.asyncio async def test_get_insight_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2037,7 +1970,7 @@ async def test_get_insight_flattened_async(): @pytest.mark.asyncio async def test_get_insight_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2099,27 +2032,6 @@ def test_mark_insight_accepted(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_mark_insight_accepted_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_insight_accepted), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_insight_accepted() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkInsightAcceptedRequest() - - def test_mark_insight_accepted_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2192,37 +2104,6 @@ def test_mark_insight_accepted_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_insight_accepted_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_insight_accepted), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - ) - response = await client.mark_insight_accepted() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkInsightAcceptedRequest() - - @pytest.mark.asyncio async def test_mark_insight_accepted_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2231,7 +2112,7 @@ async def test_mark_insight_accepted_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2271,7 +2152,7 @@ async def test_mark_insight_accepted_async( request_type=recommender_service.MarkInsightAcceptedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2353,7 +2234,7 @@ def test_mark_insight_accepted_field_headers(): @pytest.mark.asyncio async def test_mark_insight_accepted_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2435,7 +2316,7 @@ def test_mark_insight_accepted_flattened_error(): @pytest.mark.asyncio async def test_mark_insight_accepted_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2472,7 +2353,7 @@ async def test_mark_insight_accepted_flattened_async(): @pytest.mark.asyncio async def test_mark_insight_accepted_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2524,27 +2405,6 @@ def test_list_recommendations(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_recommendations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommendations), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_recommendations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendationsRequest() - - def test_list_recommendations_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2618,31 +2478,6 @@ def test_list_recommendations_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_recommendations_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommendations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListRecommendationsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_recommendations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendationsRequest() - - @pytest.mark.asyncio async def test_list_recommendations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2651,7 +2486,7 @@ async def test_list_recommendations_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2691,7 +2526,7 @@ async def test_list_recommendations_async( request_type=recommender_service.ListRecommendationsRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2761,7 +2596,7 @@ def test_list_recommendations_field_headers(): @pytest.mark.asyncio async def test_list_recommendations_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2840,7 +2675,7 @@ def test_list_recommendations_flattened_error(): @pytest.mark.asyncio async def test_list_recommendations_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2875,7 +2710,7 @@ async def test_list_recommendations_flattened_async(): @pytest.mark.asyncio async def test_list_recommendations_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2990,7 +2825,7 @@ def test_list_recommendations_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_recommendations_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3042,7 +2877,7 @@ async def test_list_recommendations_async_pager(): @pytest.mark.asyncio async def test_list_recommendations_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3138,27 +2973,6 @@ def test_get_recommendation(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_get_recommendation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommendation), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_recommendation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommendationRequest() - - def test_get_recommendation_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3228,36 +3042,6 @@ def test_get_recommendation_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_recommendation_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommendation), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.get_recommendation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommendationRequest() - - @pytest.mark.asyncio async def test_get_recommendation_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3266,7 +3050,7 @@ async def test_get_recommendation_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3306,7 +3090,7 @@ async def test_get_recommendation_async( request_type=recommender_service.GetRecommendationRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3386,7 +3170,7 @@ def test_get_recommendation_field_headers(): @pytest.mark.asyncio async def test_get_recommendation_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3460,7 +3244,7 @@ def test_get_recommendation_flattened_error(): @pytest.mark.asyncio async def test_get_recommendation_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3491,7 +3275,7 @@ async def test_get_recommendation_flattened_async(): @pytest.mark.asyncio async def test_get_recommendation_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3551,14 +3335,22 @@ def test_mark_recommendation_claimed(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_claimed_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_claimed_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = recommender_service.MarkRecommendationClaimedRequest( + name="name_value", + etag="etag_value", + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.mark_recommendation_claimed), "__call__" @@ -3566,36 +3358,7 @@ def test_mark_recommendation_claimed_empty_call(): call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mark_recommendation_claimed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationClaimedRequest() - - -def test_mark_recommendation_claimed_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = recommender_service.MarkRecommendationClaimedRequest( - name="name_value", - etag="etag_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_claimed), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_claimed(request=request) + client.mark_recommendation_claimed(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == recommender_service.MarkRecommendationClaimedRequest( @@ -3644,36 +3407,6 @@ def test_mark_recommendation_claimed_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_claimed_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_claimed), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_claimed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationClaimedRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_claimed_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3682,7 +3415,7 @@ async def test_mark_recommendation_claimed_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3722,7 +3455,7 @@ async def test_mark_recommendation_claimed_async( request_type=recommender_service.MarkRecommendationClaimedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3802,7 +3535,7 @@ def test_mark_recommendation_claimed_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3886,7 +3619,7 @@ def test_mark_recommendation_claimed_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3925,7 +3658,7 @@ async def test_mark_recommendation_claimed_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_claimed_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3987,27 +3720,6 @@ def test_mark_recommendation_succeeded(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_succeeded_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_succeeded), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_succeeded() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationSucceededRequest() - - def test_mark_recommendation_succeeded_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4080,36 +3792,6 @@ def test_mark_recommendation_succeeded_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_succeeded_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_succeeded), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_succeeded() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationSucceededRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_succeeded_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4118,7 +3800,7 @@ async def test_mark_recommendation_succeeded_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4158,7 +3840,7 @@ async def test_mark_recommendation_succeeded_async( request_type=recommender_service.MarkRecommendationSucceededRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4238,7 +3920,7 @@ def test_mark_recommendation_succeeded_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4322,7 +4004,7 @@ def test_mark_recommendation_succeeded_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4361,7 +4043,7 @@ async def test_mark_recommendation_succeeded_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_succeeded_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4423,27 +4105,6 @@ def test_mark_recommendation_failed(request_type, transport: str = "grpc"): assert response.xor_group_id == "xor_group_id_value" -def test_mark_recommendation_failed_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_failed), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.mark_recommendation_failed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationFailedRequest() - - def test_mark_recommendation_failed_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4516,36 +4177,6 @@ def test_mark_recommendation_failed_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_mark_recommendation_failed_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mark_recommendation_failed), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - ) - response = await client.mark_recommendation_failed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.MarkRecommendationFailedRequest() - - @pytest.mark.asyncio async def test_mark_recommendation_failed_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4554,7 +4185,7 @@ async def test_mark_recommendation_failed_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4594,7 +4225,7 @@ async def test_mark_recommendation_failed_async( request_type=recommender_service.MarkRecommendationFailedRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4674,7 +4305,7 @@ def test_mark_recommendation_failed_field_headers(): @pytest.mark.asyncio async def test_mark_recommendation_failed_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4758,7 +4389,7 @@ def test_mark_recommendation_failed_flattened_error(): @pytest.mark.asyncio async def test_mark_recommendation_failed_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4797,7 +4428,7 @@ async def test_mark_recommendation_failed_flattened_async(): @pytest.mark.asyncio async def test_mark_recommendation_failed_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4855,27 +4486,6 @@ def test_get_recommender_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_get_recommender_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommender_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommenderConfigRequest() - - def test_get_recommender_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4946,34 +4556,6 @@ def test_get_recommender_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_recommender_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_recommender_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.get_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetRecommenderConfigRequest() - - @pytest.mark.asyncio async def test_get_recommender_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4982,7 +4564,7 @@ async def test_get_recommender_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5022,7 +4604,7 @@ async def test_get_recommender_config_async( request_type=recommender_service.GetRecommenderConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5098,7 +4680,7 @@ def test_get_recommender_config_field_headers(): @pytest.mark.asyncio async def test_get_recommender_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5172,7 +4754,7 @@ def test_get_recommender_config_flattened_error(): @pytest.mark.asyncio async def test_get_recommender_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5203,7 +4785,7 @@ async def test_get_recommender_config_flattened_async(): @pytest.mark.asyncio async def test_get_recommender_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5259,27 +4841,6 @@ def test_update_recommender_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_recommender_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_recommender_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateRecommenderConfigRequest() - - def test_update_recommender_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5346,34 +4907,6 @@ def test_update_recommender_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_recommender_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_recommender_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.update_recommender_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateRecommenderConfigRequest() - - @pytest.mark.asyncio async def test_update_recommender_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5382,7 +4915,7 @@ async def test_update_recommender_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5422,7 +4955,7 @@ async def test_update_recommender_config_async( request_type=recommender_service.UpdateRecommenderConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5498,7 +5031,7 @@ def test_update_recommender_config_field_headers(): @pytest.mark.asyncio async def test_update_recommender_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5581,7 +5114,7 @@ def test_update_recommender_config_flattened_error(): @pytest.mark.asyncio async def test_update_recommender_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5618,7 +5151,7 @@ async def test_update_recommender_config_flattened_async(): @pytest.mark.asyncio async def test_update_recommender_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5677,27 +5210,6 @@ def test_get_insight_type_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_get_insight_type_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_insight_type_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightTypeConfigRequest() - - def test_get_insight_type_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5768,34 +5280,6 @@ def test_get_insight_type_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_insight_type_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_insight_type_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.get_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.GetInsightTypeConfigRequest() - - @pytest.mark.asyncio async def test_get_insight_type_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5804,7 +5288,7 @@ async def test_get_insight_type_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5844,7 +5328,7 @@ async def test_get_insight_type_config_async( request_type=recommender_service.GetInsightTypeConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5920,7 +5404,7 @@ def test_get_insight_type_config_field_headers(): @pytest.mark.asyncio async def test_get_insight_type_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5994,7 +5478,7 @@ def test_get_insight_type_config_flattened_error(): @pytest.mark.asyncio async def test_get_insight_type_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6025,7 +5509,7 @@ async def test_get_insight_type_config_flattened_async(): @pytest.mark.asyncio async def test_get_insight_type_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6081,27 +5565,6 @@ def test_update_insight_type_config(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_insight_type_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_insight_type_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateInsightTypeConfigRequest() - - def test_update_insight_type_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6168,34 +5631,6 @@ def test_update_insight_type_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_insight_type_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_insight_type_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - ) - response = await client.update_insight_type_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.UpdateInsightTypeConfigRequest() - - @pytest.mark.asyncio async def test_update_insight_type_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6204,7 +5639,7 @@ async def test_update_insight_type_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6244,7 +5679,7 @@ async def test_update_insight_type_config_async( request_type=recommender_service.UpdateInsightTypeConfigRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6320,7 +5755,7 @@ def test_update_insight_type_config_field_headers(): @pytest.mark.asyncio async def test_update_insight_type_config_field_headers_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6403,7 +5838,7 @@ def test_update_insight_type_config_flattened_error(): @pytest.mark.asyncio async def test_update_insight_type_config_flattened_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6440,7 +5875,7 @@ async def test_update_insight_type_config_flattened_async(): @pytest.mark.asyncio async def test_update_insight_type_config_flattened_error_async(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6493,27 +5928,6 @@ def test_list_recommenders(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_recommenders_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommenders), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_recommenders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendersRequest() - - def test_list_recommenders_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -6581,31 +5995,6 @@ def test_list_recommenders_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_recommenders_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_recommenders), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListRecommendersResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_recommenders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListRecommendersRequest() - - @pytest.mark.asyncio async def test_list_recommenders_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6614,7 +6003,7 @@ async def test_list_recommenders_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6654,7 +6043,7 @@ async def test_list_recommenders_async( request_type=recommender_service.ListRecommendersRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6789,7 +6178,7 @@ def test_list_recommenders_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_recommenders_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6841,7 +6230,7 @@ async def test_list_recommenders_async_pager(): @pytest.mark.asyncio async def test_list_recommenders_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6927,27 +6316,6 @@ def test_list_insight_types(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_insight_types_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_insight_types), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_insight_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightTypesRequest() - - def test_list_insight_types_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -7017,31 +6385,6 @@ def test_list_insight_types_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_insight_types_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_insight_types), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - recommender_service.ListInsightTypesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_insight_types() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommender_service.ListInsightTypesRequest() - - @pytest.mark.asyncio async def test_list_insight_types_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -7050,7 +6393,7 @@ async def test_list_insight_types_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7090,7 +6433,7 @@ async def test_list_insight_types_async( request_type=recommender_service.ListInsightTypesRequest, ): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7225,7 +6568,7 @@ def test_list_insight_types_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_insight_types_async_pager(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7277,7 +6620,7 @@ async def test_list_insight_types_async_pager(): @pytest.mark.asyncio async def test_list_insight_types_async_pages(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -7325,46 +6668,6 @@ async def test_list_insight_types_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.ListInsightsRequest, - dict, - ], -) -def test_list_insights_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = recommender_service.ListInsightsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_service.ListInsightsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_insights(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInsightsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_insights_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7501,108 +6804,27 @@ def test_list_insights_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_insights_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_list_insights_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), + transport="rest", ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_insights" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_list_insights" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.ListInsightsRequest.pb( - recommender_service.ListInsightsRequest() - ) - 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 = recommender_service.ListInsightsResponse.to_json( - recommender_service.ListInsightsResponse() - ) + # 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 = recommender_service.ListInsightsResponse() - request = recommender_service.ListInsightsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_service.ListInsightsResponse() + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/insightTypes/sample3" + } - client.list_insights( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_insights_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListInsightsRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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.list_insights(request) - - -def test_list_insights_rest_flattened(): - client = RecommenderClient( - 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 = recommender_service.ListInsightsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/insightTypes/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7706,60 +6928,6 @@ def test_list_insights_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetInsightRequest, - dict, - ], -) -def test_get_insight_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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 = insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight.Insight.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_insight(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight.Insight) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.target_resources == ["target_resources_value"] - assert response.insight_subtype == "insight_subtype_value" - assert response.category == insight.Insight.Category.COST - assert response.severity == insight.Insight.Severity.LOW - assert response.etag == "etag_value" - - def test_get_insight_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7879,87 +7047,6 @@ def test_get_insight_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_insight_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_insight" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetInsightRequest.pb( - recommender_service.GetInsightRequest() - ) - 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 = insight.Insight.to_json(insight.Insight()) - - request = recommender_service.GetInsightRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight.Insight() - - client.get_insight( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_insight_rest_bad_request( - transport: str = "rest", request_type=recommender_service.GetInsightRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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_insight(request) - - def test_get_insight_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8019,66 +7106,6 @@ def test_get_insight_rest_flattened_error(transport: str = "rest"): ) -def test_get_insight_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkInsightAcceptedRequest, - dict, - ], -) -def test_mark_insight_accepted_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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 = insight.Insight( - name="name_value", - description="description_value", - target_resources=["target_resources_value"], - insight_subtype="insight_subtype_value", - category=insight.Insight.Category.COST, - severity=insight.Insight.Severity.LOW, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight.Insight.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_insight_accepted(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight.Insight) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.target_resources == ["target_resources_value"] - assert response.insight_subtype == "insight_subtype_value" - assert response.category == insight.Insight.Category.COST - assert response.severity == insight.Insight.Severity.LOW - assert response.etag == "etag_value" - - def test_mark_insight_accepted_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8216,91 +7243,10 @@ def test_mark_insight_accepted_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_insight_accepted_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_mark_insight_accepted_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_insight_accepted" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_insight_accepted" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkInsightAcceptedRequest.pb( - recommender_service.MarkInsightAcceptedRequest() - ) - 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 = insight.Insight.to_json(insight.Insight()) - - request = recommender_service.MarkInsightAcceptedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight.Insight() - - client.mark_insight_accepted( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_insight_accepted_rest_bad_request( - transport: str = "rest", request_type=recommender_service.MarkInsightAcceptedRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" - } - 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.mark_insight_accepted(request) - - -def test_mark_insight_accepted_rest_flattened(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -8360,52 +7306,6 @@ def test_mark_insight_accepted_rest_flattened_error(transport: str = "rest"): ) -def test_mark_insight_accepted_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.ListRecommendationsRequest, - dict, - ], -) -def test_list_recommendations_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = recommender_service.ListRecommendationsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_service.ListRecommendationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_recommendations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRecommendationsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_recommendations_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8548,89 +7448,6 @@ def test_list_recommendations_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_recommendations_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_recommendations" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_list_recommendations" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.ListRecommendationsRequest.pb( - recommender_service.ListRecommendationsRequest() - ) - 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 = ( - recommender_service.ListRecommendationsResponse.to_json( - recommender_service.ListRecommendationsResponse() - ) - ) - - request = recommender_service.ListRecommendationsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_service.ListRecommendationsResponse() - - client.list_recommendations( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_recommendations_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListRecommendationsRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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.list_recommendations(request) - - def test_list_recommendations_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8757,58 +7574,6 @@ def test_list_recommendations_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetRecommendationRequest, - dict, - ], -) -def test_get_recommendation_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_recommendation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_get_recommendation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8932,93 +7697,10 @@ def test_get_recommendation_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recommendation_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_get_recommendation_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommendation" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_recommendation" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetRecommendationRequest.pb( - recommender_service.GetRecommendationRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.GetRecommendationRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.get_recommendation( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_recommendation_rest_bad_request( - transport: str = "rest", request_type=recommender_service.GetRecommendationRequest -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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_recommendation(request) - - -def test_get_recommendation_rest_flattened(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -9074,64 +7756,6 @@ def test_get_recommendation_rest_flattened_error(transport: str = "rest"): ) -def test_get_recommendation_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationClaimedRequest, - dict, - ], -) -def test_mark_recommendation_claimed_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_claimed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_claimed_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9269,90 +7893,6 @@ def test_mark_recommendation_claimed_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_claimed_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_claimed" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_claimed" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationClaimedRequest.pb( - recommender_service.MarkRecommendationClaimedRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationClaimedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_claimed( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_claimed_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationClaimedRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_claimed(request) - - def test_mark_recommendation_claimed_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9416,64 +7956,6 @@ def test_mark_recommendation_claimed_rest_flattened_error(transport: str = "rest ) -def test_mark_recommendation_claimed_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationSucceededRequest, - dict, - ], -) -def test_mark_recommendation_succeeded_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_succeeded(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_succeeded_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9613,94 +8095,10 @@ def test_mark_recommendation_succeeded_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_succeeded_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_mark_recommendation_succeeded_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_succeeded" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_succeeded" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationSucceededRequest.pb( - recommender_service.MarkRecommendationSucceededRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationSucceededRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_succeeded( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_succeeded_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationSucceededRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_succeeded(request) - - -def test_mark_recommendation_succeeded_rest_flattened(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -9760,64 +8158,6 @@ def test_mark_recommendation_succeeded_rest_flattened_error(transport: str = "re ) -def test_mark_recommendation_succeeded_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.MarkRecommendationFailedRequest, - dict, - ], -) -def test_mark_recommendation_failed_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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 = recommendation.Recommendation( - name="name_value", - description="description_value", - recommender_subtype="recommender_subtype_value", - priority=recommendation.Recommendation.Priority.P4, - etag="etag_value", - xor_group_id="xor_group_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation.Recommendation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.mark_recommendation_failed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation.Recommendation) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.recommender_subtype == "recommender_subtype_value" - assert response.priority == recommendation.Recommendation.Priority.P4 - assert response.etag == "etag_value" - assert response.xor_group_id == "xor_group_id_value" - - def test_mark_recommendation_failed_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9955,90 +8295,6 @@ def test_mark_recommendation_failed_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mark_recommendation_failed_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_failed" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_mark_recommendation_failed" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.MarkRecommendationFailedRequest.pb( - recommender_service.MarkRecommendationFailedRequest() - ) - 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 = recommendation.Recommendation.to_json( - recommendation.Recommendation() - ) - - request = recommender_service.MarkRecommendationFailedRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation.Recommendation() - - client.mark_recommendation_failed( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mark_recommendation_failed_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.MarkRecommendationFailedRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" - } - 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.mark_recommendation_failed(request) - - def test_mark_recommendation_failed_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10102,77 +8358,23 @@ def test_mark_recommendation_failed_rest_flattened_error(transport: str = "rest" ) -def test_mark_recommendation_failed_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetRecommenderConfigRequest, - dict, - ], -) -def test_get_recommender_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_recommender_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - request = request_type(**request_init) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # 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 = recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_config.RecommenderConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_recommender_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommender_config.RecommenderConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - -def test_get_recommender_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_recommender_config - in client._transport._wrapped_methods + # Ensure method has been cached + assert ( + client._transport.get_recommender_config + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -10280,90 +8482,6 @@ def test_get_recommender_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_recommender_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommender_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_recommender_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetRecommenderConfigRequest.pb( - recommender_service.GetRecommenderConfigRequest() - ) - 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 = recommender_config.RecommenderConfig.to_json( - recommender_config.RecommenderConfig() - ) - - request = recommender_service.GetRecommenderConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommender_config.RecommenderConfig() - - client.get_recommender_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_recommender_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.GetRecommenderConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - 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_recommender_config(request) - - def test_get_recommender_config_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10423,140 +8541,6 @@ def test_get_recommender_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_recommender_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.UpdateRecommenderConfigRequest, - dict, - ], -) -def test_update_recommender_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "recommender_config": { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - } - request_init["recommender_config"] = { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config", - "recommender_generation_config": {"params": {"fields": {}}}, - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "revision_id": "revision_id_value", - "annotations": {}, - "display_name": "display_name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = recommender_service.UpdateRecommenderConfigRequest.meta.fields[ - "recommender_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["recommender_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["recommender_config"][field])): - del request_init["recommender_config"][field][i][subfield] - else: - del request_init["recommender_config"][field][subfield] - 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 = gcr_recommender_config.RecommenderConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_recommender_config.RecommenderConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_recommender_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_recommender_config.RecommenderConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - def test_update_recommender_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10692,96 +8676,10 @@ def test_update_recommender_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_recommender_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_update_recommender_config_rest_flattened(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_recommender_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_update_recommender_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.UpdateRecommenderConfigRequest.pb( - recommender_service.UpdateRecommenderConfigRequest() - ) - 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 = gcr_recommender_config.RecommenderConfig.to_json( - gcr_recommender_config.RecommenderConfig() - ) - - request = recommender_service.UpdateRecommenderConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_recommender_config.RecommenderConfig() - - client.update_recommender_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_recommender_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.UpdateRecommenderConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "recommender_config": { - "name": "projects/sample1/locations/sample2/recommenders/sample3/config" - } - } - 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_recommender_config(request) - - -def test_update_recommender_config_rest_flattened(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -10845,60 +8743,6 @@ def test_update_recommender_config_rest_flattened_error(transport: str = "rest") ) -def test_update_recommender_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.GetInsightTypeConfigRequest, - dict, - ], -) -def test_get_insight_type_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - 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 = insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = insight_type_config.InsightTypeConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_insight_type_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, insight_type_config.InsightTypeConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - def test_get_insight_type_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11023,90 +8867,6 @@ def test_get_insight_type_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_insight_type_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight_type_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_get_insight_type_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.GetInsightTypeConfigRequest.pb( - recommender_service.GetInsightTypeConfigRequest() - ) - 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 = insight_type_config.InsightTypeConfig.to_json( - insight_type_config.InsightTypeConfig() - ) - - request = recommender_service.GetInsightTypeConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = insight_type_config.InsightTypeConfig() - - client.get_insight_type_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_insight_type_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.GetInsightTypeConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - 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_insight_type_config(request) - - def test_get_insight_type_config_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11166,158 +8926,24 @@ def test_get_insight_type_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_insight_type_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_insight_type_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.UpdateInsightTypeConfigRequest, - dict, - ], -) -def test_update_insight_type_config_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "insight_type_config": { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - } - request_init["insight_type_config"] = { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config", - "insight_type_generation_config": {"params": {"fields": {}}}, - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "revision_id": "revision_id_value", - "annotations": {}, - "display_name": "display_name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = recommender_service.UpdateInsightTypeConfigRequest.meta.fields[ - "insight_type_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["insight_type_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["insight_type_config"][field])): - del request_init["insight_type_config"][field][i][subfield] - else: - del request_init["insight_type_config"][field][subfield] - 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 = gcr_insight_type_config.InsightTypeConfig( - name="name_value", - etag="etag_value", - revision_id="revision_id_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_insight_type_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_insight_type_config.InsightTypeConfig) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.revision_id == "revision_id_value" - assert response.display_name == "display_name_value" - - -def test_update_insight_type_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_insight_type_config - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_insight_type_config + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -11435,92 +9061,6 @@ def test_update_insight_type_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_insight_type_config_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), - ) - client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_insight_type_config" - ) as post, mock.patch.object( - transports.RecommenderRestInterceptor, "pre_update_insight_type_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommender_service.UpdateInsightTypeConfigRequest.pb( - recommender_service.UpdateInsightTypeConfigRequest() - ) - 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 = gcr_insight_type_config.InsightTypeConfig.to_json( - gcr_insight_type_config.InsightTypeConfig() - ) - - request = recommender_service.UpdateInsightTypeConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_insight_type_config.InsightTypeConfig() - - client.update_insight_type_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_insight_type_config_rest_bad_request( - transport: str = "rest", - request_type=recommender_service.UpdateInsightTypeConfigRequest, -): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "insight_type_config": { - "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" - } - } - 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_insight_type_config(request) - - def test_update_insight_type_config_rest_flattened(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11588,52 +9128,6 @@ def test_update_insight_type_config_rest_flattened_error(transport: str = "rest" ) -def test_update_insight_type_config_rest_error(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - recommender_service.ListRecommendersRequest, - dict, - ], -) -def test_list_recommenders_rest(request_type): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = recommender_service.ListRecommendersResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommender_service.ListRecommendersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_recommenders(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRecommendersPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_recommenders_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -11672,20 +9166,2881 @@ def test_list_recommenders_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_recommenders_rest_interceptors(null_interceptor): - transport = transports.RecommenderRestTransport( +def test_list_recommenders_rest_pager(transport: str = "rest"): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.RecommenderRestInterceptor(), + transport=transport, ) - client = RecommenderClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + recommender_service.ListRecommendersResponse( + recommenders=[ + recommendation.RecommenderType(), + recommendation.RecommenderType(), + recommendation.RecommenderType(), + ], + next_page_token="abc", + ), + recommender_service.ListRecommendersResponse( + recommenders=[], + next_page_token="def", + ), + recommender_service.ListRecommendersResponse( + recommenders=[ + recommendation.RecommenderType(), + ], + next_page_token="ghi", + ), + recommender_service.ListRecommendersResponse( + recommenders=[ + recommendation.RecommenderType(), + recommendation.RecommenderType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + recommender_service.ListRecommendersResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_recommenders(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, recommendation.RecommenderType) for i in results) + + pages = list(client.list_recommenders(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_insight_types_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_insight_types in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_insight_types + ] = mock_rpc + + request = {} + client.list_insight_types(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_insight_types(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_insight_types_rest_pager(transport: str = "rest"): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + recommender_service.ListInsightTypesResponse( + insight_types=[ + insight.InsightType(), + insight.InsightType(), + insight.InsightType(), + ], + next_page_token="abc", + ), + recommender_service.ListInsightTypesResponse( + insight_types=[], + next_page_token="def", + ), + recommender_service.ListInsightTypesResponse( + insight_types=[ + insight.InsightType(), + ], + next_page_token="ghi", + ), + recommender_service.ListInsightTypesResponse( + insight_types=[ + insight.InsightType(), + insight.InsightType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + recommender_service.ListInsightTypesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_insight_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, insight.InsightType) for i in results) + + pages = list(client.list_insight_types(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommenderClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommenderClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommenderClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RecommenderClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommenderGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommenderGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RecommenderGrpcTransport, + transports.RecommenderGrpcAsyncIOTransport, + transports.RecommenderRestTransport, + ], +) +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_transport_kind_grpc(): + transport = RecommenderClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insights_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + call.return_value = recommender_service.ListInsightsResponse() + client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + call.return_value = insight.Insight() + client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_insight_accepted_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + call.return_value = insight.Insight() + client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommendations_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + call.return_value = recommender_service.ListRecommendationsResponse() + client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommendation_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.get_recommendation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_claimed_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_claimed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_succeeded_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_succeeded(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_failed_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + call.return_value = recommendation.Recommendation() + client.mark_recommendation_failed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommender_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + call.return_value = recommender_config.RecommenderConfig() + client.get_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_recommender_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + call.return_value = gcr_recommender_config.RecommenderConfig() + client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_type_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + call.return_value = insight_type_config.InsightTypeConfig() + client.get_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_insight_type_config_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + call.return_value = gcr_insight_type_config.InsightTypeConfig() + client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommenders_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommenders), "__call__" + ) as call: + call.return_value = recommender_service.ListRecommendersResponse() + client.list_recommenders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insight_types_empty_call_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_insight_types), "__call__" + ) as call: + call.return_value = recommender_service.ListInsightTypesResponse() + client.list_insight_types(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightTypesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RecommenderAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_insights_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_insight_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + ) + await client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_insight_accepted_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + ) + await client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_recommendations_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recommendation_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.get_recommendation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_claimed_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_claimed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_succeeded_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_succeeded(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mark_recommendation_failed_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + ) + await client.mark_recommendation_failed(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_recommender_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.get_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_recommender_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_insight_type_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.get_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_insight_type_config_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + ) + await client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_recommenders_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommenders), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListRecommendersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_recommenders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_insight_types_empty_call_grpc_asyncio(): + client = RecommenderAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_insight_types), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + recommender_service.ListInsightTypesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_insight_types(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightTypesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RecommenderClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_insights_rest_bad_request( + request_type=recommender_service.ListInsightsRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_insights(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.ListInsightsRequest, + dict, + ], +) +def test_list_insights_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/insightTypes/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 = recommender_service.ListInsightsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_service.ListInsightsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_insights(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInsightsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_insights_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_insights" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_list_insights" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.ListInsightsRequest.pb( + recommender_service.ListInsightsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_service.ListInsightsResponse.to_json( + recommender_service.ListInsightsResponse() + ) + req.return_value.content = return_value + + request = recommender_service.ListInsightsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_service.ListInsightsResponse() + + client.list_insights( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_insight_rest_bad_request( + request_type=recommender_service.GetInsightRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_insight(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetInsightRequest, + dict, + ], +) +def test_get_insight_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight.Insight.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_insight(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.target_resources == ["target_resources_value"] + assert response.insight_subtype == "insight_subtype_value" + assert response.category == insight.Insight.Category.COST + assert response.severity == insight.Insight.Severity.LOW + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_insight_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_insight" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetInsightRequest.pb( + recommender_service.GetInsightRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight.Insight.to_json(insight.Insight()) + req.return_value.content = return_value + + request = recommender_service.GetInsightRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight.Insight() + + client.get_insight( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_insight_accepted_rest_bad_request( + request_type=recommender_service.MarkInsightAcceptedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_insight_accepted(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkInsightAcceptedRequest, + dict, + ], +) +def test_mark_insight_accepted_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/insights/sample4" + } + 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 = insight.Insight( + name="name_value", + description="description_value", + target_resources=["target_resources_value"], + insight_subtype="insight_subtype_value", + category=insight.Insight.Category.COST, + severity=insight.Insight.Severity.LOW, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight.Insight.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_insight_accepted(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight.Insight) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.target_resources == ["target_resources_value"] + assert response.insight_subtype == "insight_subtype_value" + assert response.category == insight.Insight.Category.COST + assert response.severity == insight.Insight.Severity.LOW + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_insight_accepted_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_insight_accepted" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_insight_accepted" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkInsightAcceptedRequest.pb( + recommender_service.MarkInsightAcceptedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight.Insight.to_json(insight.Insight()) + req.return_value.content = return_value + + request = recommender_service.MarkInsightAcceptedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight.Insight() + + client.mark_insight_accepted( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_recommendations_rest_bad_request( + request_type=recommender_service.ListRecommendationsRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_recommendations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.ListRecommendationsRequest, + dict, + ], +) +def test_list_recommendations_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/recommenders/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 = recommender_service.ListRecommendationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_service.ListRecommendationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_recommendations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecommendationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_recommendations_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_recommendations" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_list_recommendations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.ListRecommendationsRequest.pb( + recommender_service.ListRecommendationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_service.ListRecommendationsResponse.to_json( + recommender_service.ListRecommendationsResponse() + ) + req.return_value.content = return_value + + request = recommender_service.ListRecommendationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_service.ListRecommendationsResponse() + + client.list_recommendations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_recommendation_rest_bad_request( + request_type=recommender_service.GetRecommendationRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_recommendation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetRecommendationRequest, + dict, + ], +) +def test_get_recommendation_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_recommendation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_recommendation_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommendation" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_recommendation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetRecommendationRequest.pb( + recommender_service.GetRecommendationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.GetRecommendationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.get_recommendation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_claimed_rest_bad_request( + request_type=recommender_service.MarkRecommendationClaimedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_claimed(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationClaimedRequest, + dict, + ], +) +def test_mark_recommendation_claimed_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_claimed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_claimed_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_claimed" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_claimed" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationClaimedRequest.pb( + recommender_service.MarkRecommendationClaimedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationClaimedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_claimed( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_succeeded_rest_bad_request( + request_type=recommender_service.MarkRecommendationSucceededRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_succeeded(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationSucceededRequest, + dict, + ], +) +def test_mark_recommendation_succeeded_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_succeeded(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_succeeded_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_succeeded" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_succeeded" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationSucceededRequest.pb( + recommender_service.MarkRecommendationSucceededRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationSucceededRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_succeeded( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mark_recommendation_failed_rest_bad_request( + request_type=recommender_service.MarkRecommendationFailedRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mark_recommendation_failed(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.MarkRecommendationFailedRequest, + dict, + ], +) +def test_mark_recommendation_failed_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/recommendations/sample4" + } + 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 = recommendation.Recommendation( + name="name_value", + description="description_value", + recommender_subtype="recommender_subtype_value", + priority=recommendation.Recommendation.Priority.P4, + etag="etag_value", + xor_group_id="xor_group_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommendation.Recommendation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.mark_recommendation_failed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation.Recommendation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.recommender_subtype == "recommender_subtype_value" + assert response.priority == recommendation.Recommendation.Priority.P4 + assert response.etag == "etag_value" + assert response.xor_group_id == "xor_group_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mark_recommendation_failed_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_mark_recommendation_failed" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_mark_recommendation_failed" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.MarkRecommendationFailedRequest.pb( + recommender_service.MarkRecommendationFailedRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommendation.Recommendation.to_json( + recommendation.Recommendation() + ) + req.return_value.content = return_value + + request = recommender_service.MarkRecommendationFailedRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation.Recommendation() + + client.mark_recommendation_failed( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_recommender_config_rest_bad_request( + request_type=recommender_service.GetRecommenderConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_recommender_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetRecommenderConfigRequest, + dict, + ], +) +def test_get_recommender_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + 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 = recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_config.RecommenderConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_recommender_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommender_config.RecommenderConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_recommender_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_recommender_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_recommender_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetRecommenderConfigRequest.pb( + recommender_service.GetRecommenderConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = recommender_config.RecommenderConfig.to_json( + recommender_config.RecommenderConfig() + ) + req.return_value.content = return_value + + request = recommender_service.GetRecommenderConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommender_config.RecommenderConfig() + + client.get_recommender_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_recommender_config_rest_bad_request( + request_type=recommender_service.UpdateRecommenderConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "recommender_config": { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_recommender_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.UpdateRecommenderConfigRequest, + dict, + ], +) +def test_update_recommender_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "recommender_config": { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config" + } + } + request_init["recommender_config"] = { + "name": "projects/sample1/locations/sample2/recommenders/sample3/config", + "recommender_generation_config": {"params": {"fields": {}}}, + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "revision_id": "revision_id_value", + "annotations": {}, + "display_name": "display_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = recommender_service.UpdateRecommenderConfigRequest.meta.fields[ + "recommender_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["recommender_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["recommender_config"][field])): + del request_init["recommender_config"][field][i][subfield] + else: + del request_init["recommender_config"][field][subfield] + 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 = gcr_recommender_config.RecommenderConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_recommender_config.RecommenderConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_recommender_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_recommender_config.RecommenderConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_recommender_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_recommender_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_update_recommender_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.UpdateRecommenderConfigRequest.pb( + recommender_service.UpdateRecommenderConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_recommender_config.RecommenderConfig.to_json( + gcr_recommender_config.RecommenderConfig() + ) + req.return_value.content = return_value + + request = recommender_service.UpdateRecommenderConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_recommender_config.RecommenderConfig() + + client.update_recommender_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_insight_type_config_rest_bad_request( + request_type=recommender_service.GetInsightTypeConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_insight_type_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.GetInsightTypeConfigRequest, + dict, + ], +) +def test_get_insight_type_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + 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 = insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = insight_type_config.InsightTypeConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_insight_type_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, insight_type_config.InsightTypeConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_insight_type_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_get_insight_type_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_get_insight_type_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.GetInsightTypeConfigRequest.pb( + recommender_service.GetInsightTypeConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = insight_type_config.InsightTypeConfig.to_json( + insight_type_config.InsightTypeConfig() + ) + req.return_value.content = return_value + + request = recommender_service.GetInsightTypeConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = insight_type_config.InsightTypeConfig() + + client.get_insight_type_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_insight_type_config_rest_bad_request( + request_type=recommender_service.UpdateInsightTypeConfigRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "insight_type_config": { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_insight_type_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.UpdateInsightTypeConfigRequest, + dict, + ], +) +def test_update_insight_type_config_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "insight_type_config": { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config" + } + } + request_init["insight_type_config"] = { + "name": "projects/sample1/locations/sample2/insightTypes/sample3/config", + "insight_type_generation_config": {"params": {"fields": {}}}, + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "revision_id": "revision_id_value", + "annotations": {}, + "display_name": "display_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = recommender_service.UpdateInsightTypeConfigRequest.meta.fields[ + "insight_type_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["insight_type_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["insight_type_config"][field])): + del request_init["insight_type_config"][field][i][subfield] + else: + del request_init["insight_type_config"][field][subfield] + 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 = gcr_insight_type_config.InsightTypeConfig( + name="name_value", + etag="etag_value", + revision_id="revision_id_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_insight_type_config.InsightTypeConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_insight_type_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_insight_type_config.InsightTypeConfig) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.revision_id == "revision_id_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_insight_type_config_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_update_insight_type_config" + ) as post, mock.patch.object( + transports.RecommenderRestInterceptor, "pre_update_insight_type_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommender_service.UpdateInsightTypeConfigRequest.pb( + recommender_service.UpdateInsightTypeConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_insight_type_config.InsightTypeConfig.to_json( + gcr_insight_type_config.InsightTypeConfig() + ) + req.return_value.content = return_value + + request = recommender_service.UpdateInsightTypeConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_insight_type_config.InsightTypeConfig() + + client.update_insight_type_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_recommenders_rest_bad_request( + request_type=recommender_service.ListRecommendersRequest, +): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_recommenders(request) + + +@pytest.mark.parametrize( + "request_type", + [ + recommender_service.ListRecommendersRequest, + dict, + ], +) +def test_list_recommenders_rest_call_success(request_type): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = recommender_service.ListRecommendersResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = recommender_service.ListRecommendersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_recommenders(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRecommendersPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_recommenders_rest_interceptors(null_interceptor): + transport = transports.RecommenderRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RecommenderRestInterceptor(), + ) + client = RecommenderClient(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.RecommenderRestInterceptor, "post_list_recommenders" ) as post, mock.patch.object( transports.RecommenderRestInterceptor, "pre_list_recommenders" @@ -11702,14 +12057,12 @@ def test_list_recommenders_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - recommender_service.ListRecommendersResponse.to_json( - recommender_service.ListRecommendersResponse() - ) + return_value = recommender_service.ListRecommendersResponse.to_json( + recommender_service.ListRecommendersResponse() ) + req.return_value.content = return_value request = recommender_service.ListRecommendersRequest() metadata = [ @@ -11731,14 +12084,12 @@ def test_list_recommenders_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_recommenders_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListRecommendersRequest +def test_list_insight_types_rest_bad_request( + request_type=recommender_service.ListInsightTypesRequest, ): client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {} request = request_type(**request_init) @@ -11748,74 +12099,13 @@ def test_list_recommenders_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.list_recommenders(request) - - -def test_list_recommenders_rest_pager(transport: str = "rest"): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - recommender_service.ListRecommendersResponse( - recommenders=[ - recommendation.RecommenderType(), - recommendation.RecommenderType(), - recommendation.RecommenderType(), - ], - next_page_token="abc", - ), - recommender_service.ListRecommendersResponse( - recommenders=[], - next_page_token="def", - ), - recommender_service.ListRecommendersResponse( - recommenders=[ - recommendation.RecommenderType(), - ], - next_page_token="ghi", - ), - recommender_service.ListRecommendersResponse( - recommenders=[ - recommendation.RecommenderType(), - recommendation.RecommenderType(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - recommender_service.ListRecommendersResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {} - - pager = client.list_recommenders(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, recommendation.RecommenderType) for i in results) - - pages = list(client.list_recommenders(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.list_insight_types(request) @pytest.mark.parametrize( @@ -11825,10 +12115,9 @@ def test_list_recommenders_rest_pager(transport: str = "rest"): dict, ], ) -def test_list_insight_types_rest(request_type): +def test_list_insight_types_rest_call_success(request_type): client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -11843,13 +12132,13 @@ def test_list_insight_types_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = recommender_service.ListInsightTypesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_insight_types(request) @@ -11858,46 +12147,6 @@ def test_list_insight_types_rest(request_type): assert response.next_page_token == "next_page_token_value" -def test_list_insight_types_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.list_insight_types in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_insight_types - ] = mock_rpc - - request = {} - client.list_insight_types(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_insight_types(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_insight_types_rest_interceptors(null_interceptor): transport = transports.RecommenderRestTransport( @@ -11907,6 +12156,7 @@ def test_list_insight_types_rest_interceptors(null_interceptor): else transports.RecommenderRestInterceptor(), ) client = RecommenderClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -11928,14 +12178,12 @@ def test_list_insight_types_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - recommender_service.ListInsightTypesResponse.to_json( - recommender_service.ListInsightTypesResponse() - ) + return_value = recommender_service.ListInsightTypesResponse.to_json( + recommender_service.ListInsightTypesResponse() ) + req.return_value.content = return_value request = recommender_service.ListInsightTypesRequest() metadata = [ @@ -11953,201 +12201,319 @@ def test_list_insight_types_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insights_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_insights), "__call__") as call: + client.list_insights(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_insight), "__call__") as call: + client.get_insight(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_insight_accepted_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_insight_accepted), "__call__" + ) as call: + client.mark_insight_accepted(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkInsightAcceptedRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommendations_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommendations), "__call__" + ) as call: + client.list_recommendations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommendation_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommendation), "__call__" + ) as call: + client.get_recommendation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommendationRequest() + assert args[0] == request_msg -def test_list_insight_types_rest_bad_request( - transport: str = "rest", request_type=recommender_service.ListInsightTypesRequest -): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_claimed_empty_call_rest(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_claimed), "__call__" + ) as call: + client.mark_recommendation_claimed(request=None) - # 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.list_insight_types(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationClaimedRequest() + assert args[0] == request_msg -def test_list_insight_types_rest_pager(transport: str = "rest"): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_succeeded_empty_call_rest(): client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - recommender_service.ListInsightTypesResponse( - insight_types=[ - insight.InsightType(), - insight.InsightType(), - insight.InsightType(), - ], - next_page_token="abc", - ), - recommender_service.ListInsightTypesResponse( - insight_types=[], - next_page_token="def", - ), - recommender_service.ListInsightTypesResponse( - insight_types=[ - insight.InsightType(), - ], - next_page_token="ghi", - ), - recommender_service.ListInsightTypesResponse( - insight_types=[ - insight.InsightType(), - insight.InsightType(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_succeeded), "__call__" + ) as call: + client.mark_recommendation_succeeded(request=None) - # Wrap the values into proper Response objs - response = tuple( - recommender_service.ListInsightTypesResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationSucceededRequest() - sample_request = {} + assert args[0] == request_msg - pager = client.list_insight_types(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, insight.InsightType) for i in results) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mark_recommendation_failed_empty_call_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pages = list(client.list_insight_types(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mark_recommendation_failed), "__call__" + ) as call: + client.mark_recommendation_failed(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.MarkRecommendationFailedRequest() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RecommenderGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert args[0] == request_msg - # It is an error to provide a credentials file and a transport instance. - transport = transports.RecommenderGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommenderClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.RecommenderGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_recommender_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommenderClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommenderClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_recommender_config), "__call__" + ) as call: + client.get_recommender_config(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.RecommenderGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetRecommenderConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_recommender_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = RecommenderClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_recommender_config), "__call__" + ) as call: + client.update_recommender_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateRecommenderConfigRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommenderGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_insight_type_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = RecommenderClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_insight_type_config), "__call__" + ) as call: + client.get_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.GetInsightTypeConfigRequest() + + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommenderGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_insight_type_config_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.RecommenderGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_insight_type_config), "__call__" + ) as call: + client.update_insight_type_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.UpdateInsightTypeConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_recommenders_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_recommenders), "__call__" + ) as call: + client.list_recommenders(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.RecommenderGrpcTransport, - transports.RecommenderGrpcAsyncIOTransport, - transports.RecommenderRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListRecommendersRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = RecommenderClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_insight_types_empty_call_rest(): + client = RecommenderClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_insight_types), "__call__" + ) as call: + client.list_insight_types(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = recommender_service.ListInsightTypesRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -12908,36 +13274,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = RecommenderAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RecommenderClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = RecommenderClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/async_client.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/async_client.py index c6c7cfb33a92..51d889d7c98d 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/async_client.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/async_client.py @@ -1116,11 +1116,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1173,11 +1169,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1234,11 +1226,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1291,11 +1279,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1345,11 +1329,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1402,11 +1382,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/client.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/client.py index 2fcc7b813675..3af6228f40fa 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/client.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/client.py @@ -1553,11 +1553,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1610,11 +1606,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1671,11 +1663,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1728,11 +1716,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1782,11 +1766,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1839,11 +1819,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/README.rst b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/README.rst new file mode 100644 index 000000000000..c706d9b4b460 --- /dev/null +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CloudRedisClusterTransport` is the ABC for all transports. +- public child `CloudRedisClusterGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CloudRedisClusterGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCloudRedisClusterRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CloudRedisClusterRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/base.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/base.py index e0b0937ba43d..7494772de4ab 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/base.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/base.py @@ -160,6 +160,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/grpc_asyncio.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/grpc_asyncio.py index f099cbad235a..774b8036f7b5 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/grpc_asyncio.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -256,6 +257,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -485,41 +489,80 @@ def get_cluster_certificate_authority( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_clusters: gapic_v1.method_async.wrap_method( + self.list_clusters: self._wrap_method( self.list_clusters, default_timeout=600.0, client_info=client_info, ), - self.get_cluster: gapic_v1.method_async.wrap_method( + self.get_cluster: self._wrap_method( self.get_cluster, default_timeout=600.0, client_info=client_info, ), - self.update_cluster: gapic_v1.method_async.wrap_method( + self.update_cluster: self._wrap_method( self.update_cluster, default_timeout=600.0, client_info=client_info, ), - self.delete_cluster: gapic_v1.method_async.wrap_method( + self.delete_cluster: self._wrap_method( self.delete_cluster, default_timeout=600.0, client_info=client_info, ), - self.create_cluster: gapic_v1.method_async.wrap_method( + self.create_cluster: self._wrap_method( self.create_cluster, default_timeout=600.0, client_info=client_info, ), - self.get_cluster_certificate_authority: gapic_v1.method_async.wrap_method( + self.get_cluster_certificate_authority: self._wrap_method( self.get_cluster_certificate_authority, default_timeout=600.0, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest.py index b280f43ab323..a8df3f39e973 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.redis_cluster_v1.types import cloud_redis_cluster + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCloudRedisClusterRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.redis_cluster_v1.types import cloud_redis_cluster - -from .base import CloudRedisClusterTransport -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, @@ -409,8 +399,8 @@ class CloudRedisClusterRestStub: _interceptor: CloudRedisClusterRestInterceptor -class CloudRedisClusterRestTransport(CloudRedisClusterTransport): - """REST backend transport for CloudRedisCluster. +class CloudRedisClusterRestTransport(_BaseCloudRedisClusterRestTransport): + """REST backend synchronous transport for CloudRedisCluster. Configures and manages Cloud Memorystore for Redis clusters @@ -446,7 +436,6 @@ class CloudRedisClusterRestTransport(CloudRedisClusterTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -500,21 +489,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -578,21 +558,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateCluster(CloudRedisClusterRestStub): + class _CreateCluster( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("CreateCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "clusterId": "", - } - - @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 - } + return hash("CloudRedisClusterRestTransport.CreateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -621,45 +615,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/clusters", - "body": "cluster", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_http_options() + ) request, metadata = self._interceptor.pre_create_cluster(request, metadata) - pb_request = cloud_redis_cluster.CreateClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisClusterRestTransport._CreateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -673,19 +654,34 @@ def __call__( resp = self._interceptor.post_create_cluster(resp) return resp - class _DeleteCluster(CloudRedisClusterRestStub): + class _DeleteCluster( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("DeleteCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.DeleteCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -714,38 +710,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/clusters/*}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_http_options() + ) request, metadata = self._interceptor.pre_delete_cluster(request, metadata) - pb_request = cloud_redis_cluster.DeleteClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._DeleteCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -759,19 +744,33 @@ def __call__( resp = self._interceptor.post_delete_cluster(resp) return resp - class _GetCluster(CloudRedisClusterRestStub): + class _GetCluster( + _BaseCloudRedisClusterRestTransport._BaseGetCluster, CloudRedisClusterRestStub + ): def __hash__(self): - return hash("GetCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.GetCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -797,38 +796,27 @@ def __call__( A cluster instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/clusters/*}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_http_options() + ) request, metadata = self._interceptor.pre_get_cluster(request, metadata) - pb_request = cloud_redis_cluster.GetClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._GetCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -844,19 +832,34 @@ def __call__( resp = self._interceptor.post_get_cluster(resp) return resp - class _GetClusterCertificateAuthority(CloudRedisClusterRestStub): + class _GetClusterCertificateAuthority( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("GetClusterCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.GetClusterCertificateAuthority") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -884,42 +887,29 @@ def __call__( Redis cluster certificate authority """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/clusters/*/certificateAuthority}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_get_cluster_certificate_authority( request, metadata ) - pb_request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( - request + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._GetClusterCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -935,19 +925,33 @@ def __call__( resp = self._interceptor.post_get_cluster_certificate_authority(resp) return resp - class _ListClusters(CloudRedisClusterRestStub): + class _ListClusters( + _BaseCloudRedisClusterRestTransport._BaseListClusters, CloudRedisClusterRestStub + ): def __hash__(self): - return hash("ListClusters") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.ListClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -973,38 +977,27 @@ def __call__( Response for [ListClusters][CloudRedis.ListClusters]. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/clusters", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListClusters._get_http_options() + ) request, metadata = self._interceptor.pre_list_clusters(request, metadata) - pb_request = cloud_redis_cluster.ListClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListClusters._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseListClusters._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._ListClusters._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1020,21 +1013,35 @@ def __call__( resp = self._interceptor.post_list_clusters(resp) return resp - class _UpdateCluster(CloudRedisClusterRestStub): + class _UpdateCluster( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("UpdateCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CloudRedisClusterRestTransport.UpdateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1063,45 +1070,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{cluster.name=projects/*/locations/*/clusters/*}", - "body": "cluster", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_http_options() + ) request, metadata = self._interceptor.pre_update_cluster(request, metadata) - pb_request = cloud_redis_cluster.UpdateClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisClusterRestTransport._UpdateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1173,7 +1167,34 @@ def update_cluster( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(CloudRedisClusterRestStub): + class _GetLocation( + _BaseCloudRedisClusterRestTransport._BaseGetLocation, CloudRedisClusterRestStub + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1197,32 +1218,27 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1230,8 +1246,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1239,7 +1256,35 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(CloudRedisClusterRestStub): + class _ListLocations( + _BaseCloudRedisClusterRestTransport._BaseListLocations, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1263,32 +1308,27 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1296,8 +1336,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1305,7 +1346,35 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(CloudRedisClusterRestStub): + class _CancelOperation( + _BaseCloudRedisClusterRestTransport._BaseCancelOperation, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1326,34 +1395,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1367,7 +1431,35 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(CloudRedisClusterRestStub): + class _DeleteOperation( + _BaseCloudRedisClusterRestTransport._BaseDeleteOperation, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1388,34 +1480,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1429,7 +1516,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CloudRedisClusterRestStub): + class _GetOperation( + _BaseCloudRedisClusterRestTransport._BaseGetOperation, CloudRedisClusterRestStub + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1453,32 +1567,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1486,8 +1595,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1495,7 +1605,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CloudRedisClusterRestStub): + class _ListOperations( + _BaseCloudRedisClusterRestTransport._BaseListOperations, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1519,32 +1657,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1552,8 +1685,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest_base.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest_base.py new file mode 100644 index 000000000000..f9bb8835dc00 --- /dev/null +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/services/cloud_redis_cluster/transports/rest_base.py @@ -0,0 +1,551 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.redis_cluster_v1.types import cloud_redis_cluster + +from .base import DEFAULT_CLIENT_INFO, CloudRedisClusterTransport + + +class _BaseCloudRedisClusterRestTransport(CloudRedisClusterTransport): + """Base REST backend transport for CloudRedisCluster. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/clusters", + "body": "cluster", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.CreateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/clusters/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.DeleteClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/clusters/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.GetClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetClusterCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/clusters/*/certificateAuthority}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/clusters", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.ListClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseListClusters._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{cluster.name=projects/*/locations/*/clusters/*}", + "body": "cluster", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.UpdateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCloudRedisClusterRestTransport",) diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/async_client.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/async_client.py index 7a4f1bbe2268..7a209fb1d5f3 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/async_client.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/async_client.py @@ -1116,11 +1116,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1173,11 +1169,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1234,11 +1226,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1291,11 +1279,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1345,11 +1329,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1402,11 +1382,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/client.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/client.py index 801f259cfd26..9852ea1a6e85 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/client.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/client.py @@ -1553,11 +1553,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1610,11 +1606,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1671,11 +1663,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1728,11 +1716,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1782,11 +1766,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -1839,11 +1819,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/README.rst b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/README.rst new file mode 100644 index 000000000000..c706d9b4b460 --- /dev/null +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CloudRedisClusterTransport` is the ABC for all transports. +- public child `CloudRedisClusterGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CloudRedisClusterGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCloudRedisClusterRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CloudRedisClusterRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/base.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/base.py index 48102a0c9569..18d9c0fa31f6 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/base.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/base.py @@ -160,6 +160,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/grpc_asyncio.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/grpc_asyncio.py index 9a57ef241082..b1fc12751d6e 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/grpc_asyncio.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -256,6 +257,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -485,41 +489,80 @@ def get_cluster_certificate_authority( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_clusters: gapic_v1.method_async.wrap_method( + self.list_clusters: self._wrap_method( self.list_clusters, default_timeout=600.0, client_info=client_info, ), - self.get_cluster: gapic_v1.method_async.wrap_method( + self.get_cluster: self._wrap_method( self.get_cluster, default_timeout=600.0, client_info=client_info, ), - self.update_cluster: gapic_v1.method_async.wrap_method( + self.update_cluster: self._wrap_method( self.update_cluster, default_timeout=600.0, client_info=client_info, ), - self.delete_cluster: gapic_v1.method_async.wrap_method( + self.delete_cluster: self._wrap_method( self.delete_cluster, default_timeout=600.0, client_info=client_info, ), - self.create_cluster: gapic_v1.method_async.wrap_method( + self.create_cluster: self._wrap_method( self.create_cluster, default_timeout=600.0, client_info=client_info, ), - self.get_cluster_certificate_authority: gapic_v1.method_async.wrap_method( + self.get_cluster_certificate_authority: self._wrap_method( self.get_cluster_certificate_authority, default_timeout=600.0, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest.py index 1ee6e010f804..51083fe2ac86 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.redis_cluster_v1beta1.types import cloud_redis_cluster + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCloudRedisClusterRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.redis_cluster_v1beta1.types import cloud_redis_cluster - -from .base import CloudRedisClusterTransport -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, @@ -409,8 +399,8 @@ class CloudRedisClusterRestStub: _interceptor: CloudRedisClusterRestInterceptor -class CloudRedisClusterRestTransport(CloudRedisClusterTransport): - """REST backend transport for CloudRedisCluster. +class CloudRedisClusterRestTransport(_BaseCloudRedisClusterRestTransport): + """REST backend synchronous transport for CloudRedisCluster. Configures and manages Cloud Memorystore for Redis clusters @@ -446,7 +436,6 @@ class CloudRedisClusterRestTransport(CloudRedisClusterTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -500,21 +489,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -578,21 +558,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateCluster(CloudRedisClusterRestStub): + class _CreateCluster( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("CreateCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "clusterId": "", - } - - @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 - } + return hash("CloudRedisClusterRestTransport.CreateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -621,45 +615,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/clusters", - "body": "cluster", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_http_options() + ) request, metadata = self._interceptor.pre_create_cluster(request, metadata) - pb_request = cloud_redis_cluster.CreateClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisClusterRestTransport._CreateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -673,19 +654,34 @@ def __call__( resp = self._interceptor.post_create_cluster(resp) return resp - class _DeleteCluster(CloudRedisClusterRestStub): + class _DeleteCluster( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("DeleteCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.DeleteCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -714,38 +710,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_http_options() + ) request, metadata = self._interceptor.pre_delete_cluster(request, metadata) - pb_request = cloud_redis_cluster.DeleteClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._DeleteCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -759,19 +744,33 @@ def __call__( resp = self._interceptor.post_delete_cluster(resp) return resp - class _GetCluster(CloudRedisClusterRestStub): + class _GetCluster( + _BaseCloudRedisClusterRestTransport._BaseGetCluster, CloudRedisClusterRestStub + ): def __hash__(self): - return hash("GetCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.GetCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -797,38 +796,27 @@ def __call__( A cluster instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_http_options() + ) request, metadata = self._interceptor.pre_get_cluster(request, metadata) - pb_request = cloud_redis_cluster.GetClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._GetCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -844,19 +832,34 @@ def __call__( resp = self._interceptor.post_get_cluster(resp) return resp - class _GetClusterCertificateAuthority(CloudRedisClusterRestStub): + class _GetClusterCertificateAuthority( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("GetClusterCertificateAuthority") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.GetClusterCertificateAuthority") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -884,42 +887,29 @@ def __call__( Redis cluster certificate authority """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*/certificateAuthority}", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_http_options() + ) request, metadata = self._interceptor.pre_get_cluster_certificate_authority( request, metadata ) - pb_request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( - request + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._GetClusterCertificateAuthority._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -935,19 +925,33 @@ def __call__( resp = self._interceptor.post_get_cluster_certificate_authority(resp) return resp - class _ListClusters(CloudRedisClusterRestStub): + class _ListClusters( + _BaseCloudRedisClusterRestTransport._BaseListClusters, CloudRedisClusterRestStub + ): def __hash__(self): - return hash("ListClusters") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisClusterRestTransport.ListClusters") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -973,38 +977,27 @@ def __call__( Response for [ListClusters][CloudRedis.ListClusters]. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/clusters", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListClusters._get_http_options() + ) request, metadata = self._interceptor.pre_list_clusters(request, metadata) - pb_request = cloud_redis_cluster.ListClustersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListClusters._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseListClusters._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisClusterRestTransport._ListClusters._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1020,21 +1013,35 @@ def __call__( resp = self._interceptor.post_list_clusters(resp) return resp - class _UpdateCluster(CloudRedisClusterRestStub): + class _UpdateCluster( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster, + CloudRedisClusterRestStub, + ): def __hash__(self): - return hash("UpdateCluster") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CloudRedisClusterRestTransport.UpdateCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1063,45 +1070,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{cluster.name=projects/*/locations/*/clusters/*}", - "body": "cluster", - }, - ] + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_http_options() + ) request, metadata = self._interceptor.pre_update_cluster(request, metadata) - pb_request = cloud_redis_cluster.UpdateClusterRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisClusterRestTransport._UpdateCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1173,7 +1167,34 @@ def update_cluster( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(CloudRedisClusterRestStub): + class _GetLocation( + _BaseCloudRedisClusterRestTransport._BaseGetLocation, CloudRedisClusterRestStub + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1197,32 +1218,27 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1230,8 +1246,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1239,7 +1256,35 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(CloudRedisClusterRestStub): + class _ListLocations( + _BaseCloudRedisClusterRestTransport._BaseListLocations, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1263,32 +1308,27 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1296,8 +1336,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1305,7 +1346,35 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(CloudRedisClusterRestStub): + class _CancelOperation( + _BaseCloudRedisClusterRestTransport._BaseCancelOperation, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1326,34 +1395,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1367,7 +1431,35 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(CloudRedisClusterRestStub): + class _DeleteOperation( + _BaseCloudRedisClusterRestTransport._BaseDeleteOperation, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1388,34 +1480,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1429,7 +1516,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CloudRedisClusterRestStub): + class _GetOperation( + _BaseCloudRedisClusterRestTransport._BaseGetOperation, CloudRedisClusterRestStub + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1453,32 +1567,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1486,8 +1595,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1495,7 +1605,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CloudRedisClusterRestStub): + class _ListOperations( + _BaseCloudRedisClusterRestTransport._BaseListOperations, + CloudRedisClusterRestStub, + ): + def __hash__(self): + return hash("CloudRedisClusterRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1519,32 +1657,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseCloudRedisClusterRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisClusterRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisClusterRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisClusterRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1552,8 +1685,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest_base.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest_base.py new file mode 100644 index 000000000000..599e78dfc3e4 --- /dev/null +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/services/cloud_redis_cluster/transports/rest_base.py @@ -0,0 +1,551 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.redis_cluster_v1beta1.types import cloud_redis_cluster + +from .base import DEFAULT_CLIENT_INFO, CloudRedisClusterTransport + + +class _BaseCloudRedisClusterRestTransport(CloudRedisClusterTransport): + """Base REST backend transport for CloudRedisCluster. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clusterId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/clusters", + "body": "cluster", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.CreateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseCreateCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.DeleteClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseDeleteCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.GetClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseGetCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetClusterCertificateAuthority: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/clusters/*/certificateAuthority}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseGetClusterCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListClusters: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/clusters", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.ListClustersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseListClusters._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{cluster.name=projects/*/locations/*/clusters/*}", + "body": "cluster", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis_cluster.UpdateClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisClusterRestTransport._BaseUpdateCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCloudRedisClusterRestTransport",) diff --git a/packages/google-cloud-redis-cluster/setup.py b/packages/google-cloud-redis-cluster/setup.py index 43af8d6d4851..2a3336927507 100644 --- a/packages/google-cloud-redis-cluster/setup.py +++ b/packages/google-cloud-redis-cluster/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1/test_cloud_redis_cluster.py b/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1/test_cloud_redis_cluster.py index 3e9e16ee3103..8ec31cde0635 100644 --- a/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1/test_cloud_redis_cluster.py +++ b/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1/test_cloud_redis_cluster.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,15 +65,7 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import empty_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 -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.redis_cluster_v1.services.cloud_redis_cluster import ( CloudRedisClusterAsyncClient, @@ -67,10 +76,24 @@ from google.cloud.redis_cluster_v1.types import cloud_redis_cluster +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1208,25 +1231,6 @@ def test_list_clusters(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_clusters_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.ListClustersRequest() - - def test_list_clusters_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1292,30 +1296,6 @@ def test_list_clusters_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_clusters_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.ListClustersRequest() - - @pytest.mark.asyncio async def test_list_clusters_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1324,7 +1304,7 @@ async def test_list_clusters_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1364,7 +1344,7 @@ async def test_list_clusters_async( request_type=cloud_redis_cluster.ListClustersRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1432,7 +1412,7 @@ def test_list_clusters_field_headers(): @pytest.mark.asyncio async def test_list_clusters_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1502,7 +1482,7 @@ def test_list_clusters_flattened_error(): @pytest.mark.asyncio async def test_list_clusters_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1531,7 +1511,7 @@ async def test_list_clusters_flattened_async(): @pytest.mark.asyncio async def test_list_clusters_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1641,7 +1621,7 @@ def test_list_clusters_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_clusters_async_pager(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1691,7 +1671,7 @@ async def test_list_clusters_async_pager(): @pytest.mark.asyncio async def test_list_clusters_async_pages(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1799,25 +1779,6 @@ def test_get_cluster(request_type, transport: str = "grpc"): assert response.deletion_protection_enabled is True -def test_get_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterRequest() - - def test_get_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1881,39 +1842,6 @@ def test_get_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.Cluster( - name="name_value", - state=cloud_redis_cluster.Cluster.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, - transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, - size_gb=739, - shard_count=1178, - node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, - precise_size_gb=0.15810000000000002, - deletion_protection_enabled=True, - ) - ) - response = await client.get_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterRequest() - - @pytest.mark.asyncio async def test_get_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1922,7 +1850,7 @@ async def test_get_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1961,7 +1889,7 @@ async def test_get_cluster_async( transport: str = "grpc_asyncio", request_type=cloud_redis_cluster.GetClusterRequest ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2053,7 +1981,7 @@ def test_get_cluster_field_headers(): @pytest.mark.asyncio async def test_get_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2123,7 +2051,7 @@ def test_get_cluster_flattened_error(): @pytest.mark.asyncio async def test_get_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2152,7 +2080,7 @@ async def test_get_cluster_flattened_async(): @pytest.mark.asyncio async def test_get_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2197,25 +2125,6 @@ def test_update_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.UpdateClusterRequest() - - def test_update_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2284,27 +2193,6 @@ def test_update_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.UpdateClusterRequest() - - @pytest.mark.asyncio async def test_update_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2313,7 +2201,7 @@ async def test_update_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2358,7 +2246,7 @@ async def test_update_cluster_async( request_type=cloud_redis_cluster.UpdateClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2421,7 +2309,7 @@ def test_update_cluster_field_headers(): @pytest.mark.asyncio async def test_update_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2496,7 +2384,7 @@ def test_update_cluster_flattened_error(): @pytest.mark.asyncio async def test_update_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2529,7 +2417,7 @@ async def test_update_cluster_flattened_async(): @pytest.mark.asyncio async def test_update_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2575,25 +2463,6 @@ def test_delete_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.DeleteClusterRequest() - - def test_delete_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2664,27 +2533,6 @@ def test_delete_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.DeleteClusterRequest() - - @pytest.mark.asyncio async def test_delete_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2693,7 +2541,7 @@ async def test_delete_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2738,7 +2586,7 @@ async def test_delete_cluster_async( request_type=cloud_redis_cluster.DeleteClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2801,7 +2649,7 @@ def test_delete_cluster_field_headers(): @pytest.mark.asyncio async def test_delete_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2871,7 +2719,7 @@ def test_delete_cluster_flattened_error(): @pytest.mark.asyncio async def test_delete_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2900,7 +2748,7 @@ async def test_delete_cluster_flattened_async(): @pytest.mark.asyncio async def test_delete_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2945,25 +2793,6 @@ def test_create_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.CreateClusterRequest() - - def test_create_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3036,27 +2865,6 @@ def test_create_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.CreateClusterRequest() - - @pytest.mark.asyncio async def test_create_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3065,7 +2873,7 @@ async def test_create_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3110,7 +2918,7 @@ async def test_create_cluster_async( request_type=cloud_redis_cluster.CreateClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3173,7 +2981,7 @@ def test_create_cluster_field_headers(): @pytest.mark.asyncio async def test_create_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3253,7 +3061,7 @@ def test_create_cluster_flattened_error(): @pytest.mark.asyncio async def test_create_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3290,7 +3098,7 @@ async def test_create_cluster_flattened_async(): @pytest.mark.asyncio async def test_create_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3342,27 +3150,6 @@ def test_get_cluster_certificate_authority(request_type, transport: str = "grpc" assert response.name == "name_value" -def test_get_cluster_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_cluster_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - - def test_get_cluster_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3433,31 +3220,6 @@ def test_get_cluster_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_cluster_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.CertificateAuthority( - name="name_value", - ) - ) - response = await client.get_cluster_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_get_cluster_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3466,7 +3228,7 @@ async def test_get_cluster_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3506,7 +3268,7 @@ async def test_get_cluster_certificate_authority_async( request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3576,7 +3338,7 @@ def test_get_cluster_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3650,7 +3412,7 @@ def test_get_cluster_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3681,7 +3443,7 @@ async def test_get_cluster_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3693,48 +3455,6 @@ async def test_get_cluster_certificate_authority_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.ListClustersRequest, - dict, - ], -) -def test_list_clusters_rest(request_type): - client = CloudRedisClusterClient( - 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 = cloud_redis_cluster.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_clusters_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3869,87 +3589,6 @@ def test_list_clusters_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_list_clusters" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_list_clusters" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.ListClustersRequest.pb( - cloud_redis_cluster.ListClustersRequest() - ) - 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 = cloud_redis_cluster.ListClustersResponse.to_json( - cloud_redis_cluster.ListClustersResponse() - ) - - request = cloud_redis_cluster.ListClustersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.ListClustersResponse() - - client.list_clusters( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_clusters_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.ListClustersRequest -): - client = CloudRedisClusterClient( - 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.list_clusters(request) - - def test_list_clusters_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4069,72 +3708,6 @@ def test_list_clusters_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.GetClusterRequest, - dict, - ], -) -def test_get_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = cloud_redis_cluster.Cluster( - name="name_value", - state=cloud_redis_cluster.Cluster.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, - transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, - size_gb=739, - shard_count=1178, - node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, - precise_size_gb=0.15810000000000002, - deletion_protection_enabled=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis_cluster.Cluster) - assert response.name == "name_value" - assert response.state == cloud_redis_cluster.Cluster.State.CREATING - assert response.uid == "uid_value" - assert response.replica_count == 1384 - assert ( - response.authorization_mode - == cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH - ) - assert ( - response.transit_encryption_mode - == cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED - ) - assert response.size_gb == 739 - assert response.shard_count == 1178 - assert response.node_type == cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO - assert math.isclose(response.precise_size_gb, 0.15810000000000002, rel_tol=1e-6) - assert response.deletion_protection_enabled is True - - def test_get_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4254,117 +3827,36 @@ def test_get_cluster_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_get_cluster_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), + transport="rest", ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_get_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_get_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.GetClusterRequest.pb( - cloud_redis_cluster.GetClusterRequest() - ) - 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 = cloud_redis_cluster.Cluster.to_json( - cloud_redis_cluster.Cluster() - ) + # 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 = cloud_redis_cluster.Cluster() - request = cloud_redis_cluster.GetClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.Cluster() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - client.get_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis_cluster.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_get_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.GetClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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.get_cluster(request) - - -def test_get_cluster_rest_flattened(): - client = CloudRedisClusterClient( - 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 = cloud_redis_cluster.Cluster() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/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 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_cluster(**mock_args) + client.get_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -4391,153 +3883,6 @@ def test_get_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_get_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.UpdateClusterRequest, - dict, - ], -) -def test_update_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "size_gb": 739, - "shard_count": 1178, - "psc_configs": [{"network": "network_value"}], - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "psc_config": {}} - ], - "psc_connections": [ - { - "psc_connection_id": "psc_connection_id_value", - "address": "address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - } - ], - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "redis_configs": {}, - "precise_size_gb": 0.15810000000000002, - "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, - "deletion_protection_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis_cluster.UpdateClusterRequest.meta.fields["cluster"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4674,113 +4019,28 @@ def test_update_cluster_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_update_cluster_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), + transport="rest", ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_update_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_update_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.UpdateClusterRequest.pb( - cloud_redis_cluster.UpdateClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = cloud_redis_cluster.UpdateClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } - client.update_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + cluster=cloud_redis_cluster.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.UpdateClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/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.update_cluster(request) - - -def test_update_cluster_rest_flattened(): - client = CloudRedisClusterClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - cluster=cloud_redis_cluster.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -4818,47 +4078,6 @@ def test_update_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_update_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.DeleteClusterRequest, - dict, - ], -) -def test_delete_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4981,89 +4200,6 @@ def test_delete_cluster_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_delete_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_delete_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.DeleteClusterRequest.pb( - cloud_redis_cluster.DeleteClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis_cluster.DeleteClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.DeleteClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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.delete_cluster(request) - - def test_delete_cluster_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5118,179 +4254,34 @@ def test_delete_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_delete_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.CreateClusterRequest, - dict, - ], -) -def test_create_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "size_gb": 739, - "shard_count": 1178, - "psc_configs": [{"network": "network_value"}], - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "psc_config": {}} - ], - "psc_connections": [ - { - "psc_connection_id": "psc_connection_id_value", - "address": "address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - } - ], - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "redis_configs": {}, - "precise_size_gb": 0.15810000000000002, - "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, - "deletion_protection_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis_cluster.CreateClusterRequest.meta.fields["cluster"] + request = {} + client.create_cluster(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - - request = {} - client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 # Operation methods build a cached wrapper on first rpc call # subsequent calls should use the cached wrapper @@ -5418,89 +4409,6 @@ def test_create_cluster_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_create_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_create_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.CreateClusterRequest.pb( - cloud_redis_cluster.CreateClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis_cluster.CreateClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.CreateClusterRequest -): - client = CloudRedisClusterClient( - 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.create_cluster(request) - - def test_create_cluster_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5559,54 +4467,6 @@ def test_create_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_create_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.GetClusterCertificateAuthorityRequest, - dict, - ], -) -def test_get_cluster_certificate_authority_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" - } - 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 = cloud_redis_cluster.CertificateAuthority( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_cluster_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis_cluster.CertificateAuthority) - assert response.name == "name_value" - - def test_get_cluster_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5733,96 +4593,10 @@ def test_get_cluster_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_get_cluster_certificate_authority_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, - "post_get_cluster_certificate_authority", - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, - "pre_get_cluster_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( - cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - ) - 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 = cloud_redis_cluster.CertificateAuthority.to_json( - cloud_redis_cluster.CertificateAuthority() - ) - - request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.CertificateAuthority() - - client.get_cluster_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_cluster_certificate_authority_rest_bad_request( - transport: str = "rest", - request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" - } - 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_cluster_certificate_authority(request) - - -def test_get_cluster_certificate_authority_rest_flattened(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5880,12 +4654,6 @@ def test_get_cluster_certificate_authority_rest_flattened_error( ) -def test_get_cluster_certificate_authority_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudRedisClusterGrpcTransport( @@ -5978,1065 +4746,2462 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CloudRedisClusterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = CloudRedisClusterClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.CloudRedisClusterGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_clusters_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + call.return_value = cloud_redis_cluster.ListClustersResponse() + client.list_clusters(request=None) -def test_cloud_redis_cluster_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudRedisClusterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CloudRedisClusterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_clusters", - "get_cluster", - "update_cluster", - "delete_cluster", - "create_cluster", - "get_cluster_certificate_authority", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + call.return_value = cloud_redis_cluster.Cluster() + client.get_cluster(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_cloud_redis_cluster_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.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisClusterTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_cluster(request=None) -def test_cloud_redis_cluster_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisClusterTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudRedisClusterClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_cluster(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - transports.CloudRedisClusterRestTransport, - ], -) -def test_cloud_redis_cluster_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudRedisClusterGrpcTransport, grpc_helpers), - (transports.CloudRedisClusterGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_cloud_redis_cluster_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - create_channel.assert_called_with( - "redis.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="redis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_cluster(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() -def test_cloud_redis_cluster_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.CloudRedisClusterRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_cloud_redis_cluster_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_certificate_authority_empty_call_grpc(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + call.return_value = cloud_redis_cluster.CertificateAuthority() + client.get_cluster_certificate_authority(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_cluster_host_no_port(transport_name): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com" + +def test_transport_kind_grpc_asyncio(): + transport = CloudRedisClusterAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) + assert transport.kind == "grpc_asyncio" -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_cluster_host_with_port(transport_name): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com:8000" +def test_initialize_client_w_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) + assert client is not None -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_cloud_redis_cluster_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CloudRedisClusterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CloudRedisClusterClient( - credentials=creds2, - transport=transport_name, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_clusters_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - session1 = client1.transport.list_clusters._session - session2 = client2.transport.list_clusters._session - assert session1 != session2 - session1 = client1.transport.get_cluster._session - session2 = client2.transport.get_cluster._session - assert session1 != session2 - session1 = client1.transport.update_cluster._session - session2 = client2.transport.update_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_cluster._session - session2 = client2.transport.delete_cluster._session - assert session1 != session2 - session1 = client1.transport.create_cluster._session - session2 = client2.transport.create_cluster._session - assert session1 != session2 - session1 = client1.transport.get_cluster_certificate_authority._session - session2 = client2.transport.get_cluster_certificate_authority._session - assert session1 != session2 + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() -def test_cloud_redis_cluster_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + assert args[0] == request_msg - # Check that channel is used if provided. - transport = transports.CloudRedisClusterGrpcTransport( - host="squid.clam.whelk", - channel=channel, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.Cluster( + name="name_value", + state=cloud_redis_cluster.Cluster.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, + transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, + size_gb=739, + shard_count=1178, + node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, + precise_size_gb=0.15810000000000002, + deletion_protection_enabled=True, + ) + ) + await client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() -def test_cloud_redis_cluster_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + assert args[0] == request_msg - # Check that channel is used if provided. - transport = transports.CloudRedisClusterGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_cluster(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + assert args[0] == request_msg - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - -def test_cloud_redis_cluster_grpc_lro_client(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_cluster(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_grpc_lro_async_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_cluster_empty_call_grpc_asyncio(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_cluster(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() + assert args[0] == request_msg -def test_certificate_authority_path(): - project = "squid" - location = "clam" - cluster = "whelk" - expected = "projects/{project}/locations/{location}/clusters/{cluster}/certificateAuthority".format( - project=project, - location=location, - cluster=cluster, - ) - actual = CloudRedisClusterClient.certificate_authority_path( - project, location, cluster + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_cluster_certificate_authority_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.CertificateAuthority( + name="name_value", + ) + ) + await client.get_cluster_certificate_authority(request=None) -def test_parse_certificate_authority_path(): - expected = { - "project": "octopus", - "location": "oyster", - "cluster": "nudibranch", - } - path = CloudRedisClusterClient.certificate_authority_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_certificate_authority_path(path) - assert expected == actual + assert args[0] == request_msg -def test_cluster_path(): - project = "cuttlefish" - location = "mussel" - cluster = "winkle" - expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( - project=project, - location=location, - cluster=cluster, +def test_transport_kind_rest(): + transport = CloudRedisClusterClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() ) - actual = CloudRedisClusterClient.cluster_path(project, location, cluster) - assert expected == actual + assert transport.kind == "rest" -def test_parse_cluster_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "cluster": "abalone", - } - path = CloudRedisClusterClient.cluster_path(**expected) +def test_list_clusters_rest_bad_request( + request_type=cloud_redis_cluster.ListClustersRequest, +): + client = CloudRedisClusterClient( + 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) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_cluster_path(path) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_clusters(request) -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.ListClustersRequest, + dict, + ], +) +def test_list_clusters_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = CloudRedisClusterClient.common_billing_account_path(billing_account) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = CloudRedisClusterClient.common_billing_account_path(**expected) + # 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 = cloud_redis_cluster.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_billing_account_path(path) - assert expected == actual + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis_cluster.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_clusters(request) -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = CloudRedisClusterClient.common_folder_path(folder) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = CloudRedisClusterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_folder_path(path) - assert expected == actual +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_list_clusters" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_list_clusters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.ListClustersRequest.pb( + cloud_redis_cluster.ListClustersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = CloudRedisClusterClient.common_organization_path(organization) - assert expected == actual + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.ListClustersResponse.to_json( + cloud_redis_cluster.ListClustersResponse() + ) + req.return_value.content = return_value + request = cloud_redis_cluster.ListClustersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.ListClustersResponse() -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = CloudRedisClusterClient.common_organization_path(**expected) + client.list_clusters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_organization_path(path) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, +def test_get_cluster_rest_bad_request( + request_type=cloud_redis_cluster.GetClusterRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = CloudRedisClusterClient.common_project_path(project) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_cluster(request) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = CloudRedisClusterClient.common_project_path(**expected) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_project_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = CloudRedisClusterClient.common_location_path(project, location) - assert expected == actual + # 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 = cloud_redis_cluster.Cluster( + name="name_value", + state=cloud_redis_cluster.Cluster.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, + transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, + size_gb=739, + shard_count=1178, + node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, + precise_size_gb=0.15810000000000002, + deletion_protection_enabled=True, + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = CloudRedisClusterClient.common_location_path(**expected) + # Convert return value to protobuf type + return_value = cloud_redis_cluster.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster(request) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_location_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis_cluster.Cluster) + assert response.name == "name_value" + assert response.state == cloud_redis_cluster.Cluster.State.CREATING + assert response.uid == "uid_value" + assert response.replica_count == 1384 + assert ( + response.authorization_mode + == cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH + ) + assert ( + response.transit_encryption_mode + == cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED + ) + assert response.size_gb == 739 + assert response.shard_count == 1178 + assert response.node_type == cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO + assert math.isclose(response.precise_size_gb, 0.15810000000000002, rel_tol=1e-6) + assert response.deletion_protection_enabled is True -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) with mock.patch.object( - transports.CloudRedisClusterTransport, "_prep_wrapped_messages" - ) as prep: - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_get_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_get_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.GetClusterRequest.pb( + cloud_redis_cluster.GetClusterRequest() ) - prep.assert_called_once_with(client_info) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - with mock.patch.object( - transports.CloudRedisClusterTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = CloudRedisClusterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.Cluster.to_json( + cloud_redis_cluster.Cluster() ) - prep.assert_called_once_with(client_info) + req.return_value.content = return_value + request = cloud_redis_cluster.GetClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.Cluster() -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + client.get_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest +def test_update_cluster_rest_bad_request( + request_type=cloud_redis_cluster.UpdateClusterRequest, ): client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_location(request) + client.update_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.UpdateClusterRequest, + dict, + ], +) +def test_update_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "name": "projects/sample1/locations/sample2/clusters/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "size_gb": 739, + "shard_count": 1178, + "psc_configs": [{"network": "network_value"}], + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "psc_config": {}} + ], + "psc_connections": [ + { + "psc_connection_id": "psc_connection_id_value", + "address": "address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + } + ], + "state_info": { + "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} + }, + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "redis_configs": {}, + "precise_size_gb": 0.15810000000000002, + "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, + "deletion_protection_enabled": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis_cluster.UpdateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_update_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_update_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.UpdateClusterRequest.pb( + cloud_redis_cluster.UpdateClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.UpdateClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request( + request_type=cloud_redis_cluster.DeleteClusterRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.DeleteClusterRequest, + dict, + ], +) +def test_delete_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_delete_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_delete_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.DeleteClusterRequest.pb( + cloud_redis_cluster.DeleteClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.DeleteClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request( + request_type=cloud_redis_cluster.CreateClusterRequest, +): + client = CloudRedisClusterClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "size_gb": 739, + "shard_count": 1178, + "psc_configs": [{"network": "network_value"}], + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "psc_config": {}} + ], + "psc_connections": [ + { + "psc_connection_id": "psc_connection_id_value", + "address": "address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + } + ], + "state_info": { + "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} + }, + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "redis_configs": {}, + "precise_size_gb": 0.15810000000000002, + "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, + "deletion_protection_enabled": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis_cluster.CreateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_create_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_create_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.CreateClusterRequest.pb( + cloud_redis_cluster.CreateClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.CreateClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_certificate_authority_rest_bad_request( + request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_cluster_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.GetClusterCertificateAuthorityRequest, + dict, + ], +) +def test_get_cluster_certificate_authority_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" + } + 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 = cloud_redis_cluster.CertificateAuthority( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis_cluster.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis_cluster.CertificateAuthority) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, + "post_get_cluster_certificate_authority", + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, + "pre_get_cluster_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( + cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.CertificateAuthority.to_json( + cloud_redis_cluster.CertificateAuthority() + ) + req.return_value.content = return_value + + request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.CertificateAuthority() + + client.get_cluster_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_clusters_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + client.update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + client.delete_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + client.create_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_certificate_authority_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + client.get_cluster_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + + assert args[0] == request_msg + + +def test_cloud_redis_cluster_rest_lro_client(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudRedisClusterGrpcTransport, + ) + + +def test_cloud_redis_cluster_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudRedisClusterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_redis_cluster_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudRedisClusterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_clusters", + "get_cluster", + "update_cluster", + "delete_cluster", + "create_cluster", + "get_cluster_certificate_authority", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_redis_cluster_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.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisClusterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_redis_cluster_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.redis_cluster_v1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisClusterTransport() + adc.assert_called_once() + + +def test_cloud_redis_cluster_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudRedisClusterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + transports.CloudRedisClusterRestTransport, + ], +) +def test_cloud_redis_cluster_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudRedisClusterGrpcTransport, grpc_helpers), + (transports.CloudRedisClusterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_redis_cluster_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "redis.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="redis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_redis_cluster_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.CloudRedisClusterRestTransport( + 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_cloud_redis_cluster_host_no_port(transport_name): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "redis.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_redis_cluster_host_with_port(transport_name): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "redis.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_redis_cluster_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudRedisClusterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudRedisClusterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.get_cluster_certificate_authority._session + session2 = client2.transport.get_cluster_certificate_authority._session + assert session1 != session2 + + +def test_cloud_redis_cluster_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudRedisClusterGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_redis_cluster_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudRedisClusterGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "request_type", + "transport_class", [ - locations_pb2.GetLocationRequest, - dict, + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, ], ) -def test_get_location_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_cloud_redis_cluster_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() - response = client.get_location(request) + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): +def test_cloud_redis_cluster_grpc_lro_client(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - - # 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.list_locations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_locations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = CloudRedisClusterClient( +def test_cloud_redis_cluster_grpc_lro_async_client(): + client = CloudRedisClusterAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc_asyncio", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, ) - # 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.cancel_operation(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_certificate_authority_path(): + project = "squid" + location = "clam" + cluster = "whelk" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/certificateAuthority".format( + project=project, + location=location, + cluster=cluster, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + actual = CloudRedisClusterClient.certificate_authority_path( + project, location, cluster + ) + assert expected == actual - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_parse_certificate_authority_path(): + expected = { + "project": "octopus", + "location": "oyster", + "cluster": "nudibranch", + } + path = CloudRedisClusterClient.certificate_authority_path(**expected) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_certificate_authority_path(path) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( + project=project, + location=location, + cluster=cluster, ) - - # 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.delete_operation(request) + actual = CloudRedisClusterClient.cluster_path(project, location, cluster) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = CloudRedisClusterClient.cluster_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_cluster_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudRedisClusterClient.common_billing_account_path(billing_account) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = CloudRedisClusterClient.common_billing_account_path(**expected) -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_billing_account_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, ) + actual = CloudRedisClusterClient.common_folder_path(folder) + assert expected == actual - # 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_operation(request) +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = CloudRedisClusterClient.common_folder_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_folder_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudRedisClusterClient.common_organization_path(organization) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = CloudRedisClusterClient.common_organization_path(**expected) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_organization_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, ) + actual = CloudRedisClusterClient.common_project_path(project) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = CloudRedisClusterClient.common_project_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + actual = CloudRedisClusterClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = CloudRedisClusterClient.common_location_path(**expected) - response = client.list_operations(request) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudRedisClusterTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudRedisClusterTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudRedisClusterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -7066,7 +7231,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7119,7 +7284,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7164,7 +7329,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -7205,7 +7370,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7258,7 +7423,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7303,7 +7468,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -7344,7 +7509,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7399,7 +7564,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7446,7 +7611,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -7489,7 +7654,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7544,7 +7709,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7591,7 +7756,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -7634,7 +7799,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7689,7 +7854,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7736,7 +7901,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -7779,7 +7944,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7831,9 +7996,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) + client = CloudRedisClusterAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -7879,7 +8042,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -7895,22 +8058,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1beta1/test_cloud_redis_cluster.py b/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1beta1/test_cloud_redis_cluster.py index 3f57fb453d37..c6b89d5ea4c0 100644 --- a/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1beta1/test_cloud_redis_cluster.py +++ b/packages/google-cloud-redis-cluster/tests/unit/gapic/redis_cluster_v1beta1/test_cloud_redis_cluster.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,15 +65,7 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import empty_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 -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.redis_cluster_v1beta1.services.cloud_redis_cluster import ( CloudRedisClusterAsyncClient, @@ -67,10 +76,24 @@ from google.cloud.redis_cluster_v1beta1.types import cloud_redis_cluster +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1208,25 +1231,6 @@ def test_list_clusters(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_clusters_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.ListClustersRequest() - - def test_list_clusters_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1292,30 +1296,6 @@ def test_list_clusters_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_clusters_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_clusters() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.ListClustersRequest() - - @pytest.mark.asyncio async def test_list_clusters_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1324,7 +1304,7 @@ async def test_list_clusters_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1364,7 +1344,7 @@ async def test_list_clusters_async( request_type=cloud_redis_cluster.ListClustersRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1432,7 +1412,7 @@ def test_list_clusters_field_headers(): @pytest.mark.asyncio async def test_list_clusters_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1502,7 +1482,7 @@ def test_list_clusters_flattened_error(): @pytest.mark.asyncio async def test_list_clusters_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1531,7 +1511,7 @@ async def test_list_clusters_flattened_async(): @pytest.mark.asyncio async def test_list_clusters_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1641,7 +1621,7 @@ def test_list_clusters_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_clusters_async_pager(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1691,7 +1671,7 @@ async def test_list_clusters_async_pager(): @pytest.mark.asyncio async def test_list_clusters_async_pages(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1799,25 +1779,6 @@ def test_get_cluster(request_type, transport: str = "grpc"): assert response.deletion_protection_enabled is True -def test_get_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterRequest() - - def test_get_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1881,39 +1842,6 @@ def test_get_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.Cluster( - name="name_value", - state=cloud_redis_cluster.Cluster.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, - transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, - size_gb=739, - shard_count=1178, - node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, - precise_size_gb=0.15810000000000002, - deletion_protection_enabled=True, - ) - ) - response = await client.get_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterRequest() - - @pytest.mark.asyncio async def test_get_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1922,7 +1850,7 @@ async def test_get_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1961,7 +1889,7 @@ async def test_get_cluster_async( transport: str = "grpc_asyncio", request_type=cloud_redis_cluster.GetClusterRequest ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2053,7 +1981,7 @@ def test_get_cluster_field_headers(): @pytest.mark.asyncio async def test_get_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2123,7 +2051,7 @@ def test_get_cluster_flattened_error(): @pytest.mark.asyncio async def test_get_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2152,7 +2080,7 @@ async def test_get_cluster_flattened_async(): @pytest.mark.asyncio async def test_get_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2197,25 +2125,6 @@ def test_update_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.UpdateClusterRequest() - - def test_update_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2284,27 +2193,6 @@ def test_update_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.UpdateClusterRequest() - - @pytest.mark.asyncio async def test_update_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2313,7 +2201,7 @@ async def test_update_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2358,7 +2246,7 @@ async def test_update_cluster_async( request_type=cloud_redis_cluster.UpdateClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2421,7 +2309,7 @@ def test_update_cluster_field_headers(): @pytest.mark.asyncio async def test_update_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2496,7 +2384,7 @@ def test_update_cluster_flattened_error(): @pytest.mark.asyncio async def test_update_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2529,7 +2417,7 @@ async def test_update_cluster_flattened_async(): @pytest.mark.asyncio async def test_update_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2575,25 +2463,6 @@ def test_delete_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.DeleteClusterRequest() - - def test_delete_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2664,27 +2533,6 @@ def test_delete_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.DeleteClusterRequest() - - @pytest.mark.asyncio async def test_delete_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2693,7 +2541,7 @@ async def test_delete_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2738,7 +2586,7 @@ async def test_delete_cluster_async( request_type=cloud_redis_cluster.DeleteClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2801,7 +2649,7 @@ def test_delete_cluster_field_headers(): @pytest.mark.asyncio async def test_delete_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2871,7 +2719,7 @@ def test_delete_cluster_flattened_error(): @pytest.mark.asyncio async def test_delete_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2900,7 +2748,7 @@ async def test_delete_cluster_flattened_async(): @pytest.mark.asyncio async def test_delete_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2945,25 +2793,6 @@ def test_create_cluster(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_cluster_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.CreateClusterRequest() - - def test_create_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3036,27 +2865,6 @@ def test_create_cluster_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_cluster_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_cluster() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.CreateClusterRequest() - - @pytest.mark.asyncio async def test_create_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3065,7 +2873,7 @@ async def test_create_cluster_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3110,7 +2918,7 @@ async def test_create_cluster_async( request_type=cloud_redis_cluster.CreateClusterRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3173,7 +2981,7 @@ def test_create_cluster_field_headers(): @pytest.mark.asyncio async def test_create_cluster_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3253,7 +3061,7 @@ def test_create_cluster_flattened_error(): @pytest.mark.asyncio async def test_create_cluster_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3290,7 +3098,7 @@ async def test_create_cluster_flattened_async(): @pytest.mark.asyncio async def test_create_cluster_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3342,27 +3150,6 @@ def test_get_cluster_certificate_authority(request_type, transport: str = "grpc" assert response.name == "name_value" -def test_get_cluster_certificate_authority_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster_certificate_authority), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_cluster_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - - def test_get_cluster_certificate_authority_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3433,31 +3220,6 @@ def test_get_cluster_certificate_authority_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_cluster_certificate_authority_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis_cluster.CertificateAuthority( - name="name_value", - ) - ) - response = await client.get_cluster_certificate_authority() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - - @pytest.mark.asyncio async def test_get_cluster_certificate_authority_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3466,7 +3228,7 @@ async def test_get_cluster_certificate_authority_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3506,7 +3268,7 @@ async def test_get_cluster_certificate_authority_async( request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, ): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3576,7 +3338,7 @@ def test_get_cluster_certificate_authority_field_headers(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3650,7 +3412,7 @@ def test_get_cluster_certificate_authority_flattened_error(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_flattened_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3681,7 +3443,7 @@ async def test_get_cluster_certificate_authority_flattened_async(): @pytest.mark.asyncio async def test_get_cluster_certificate_authority_flattened_error_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3693,48 +3455,6 @@ async def test_get_cluster_certificate_authority_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.ListClustersRequest, - dict, - ], -) -def test_list_clusters_rest(request_type): - client = CloudRedisClusterClient( - 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 = cloud_redis_cluster.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_clusters_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3869,87 +3589,6 @@ def test_list_clusters_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_list_clusters" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_list_clusters" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.ListClustersRequest.pb( - cloud_redis_cluster.ListClustersRequest() - ) - 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 = cloud_redis_cluster.ListClustersResponse.to_json( - cloud_redis_cluster.ListClustersResponse() - ) - - request = cloud_redis_cluster.ListClustersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.ListClustersResponse() - - client.list_clusters( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_clusters_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.ListClustersRequest -): - client = CloudRedisClusterClient( - 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.list_clusters(request) - - def test_list_clusters_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4070,72 +3709,6 @@ def test_list_clusters_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.GetClusterRequest, - dict, - ], -) -def test_get_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = cloud_redis_cluster.Cluster( - name="name_value", - state=cloud_redis_cluster.Cluster.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, - transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, - size_gb=739, - shard_count=1178, - node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, - precise_size_gb=0.15810000000000002, - deletion_protection_enabled=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis_cluster.Cluster) - assert response.name == "name_value" - assert response.state == cloud_redis_cluster.Cluster.State.CREATING - assert response.uid == "uid_value" - assert response.replica_count == 1384 - assert ( - response.authorization_mode - == cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH - ) - assert ( - response.transit_encryption_mode - == cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED - ) - assert response.size_gb == 739 - assert response.shard_count == 1178 - assert response.node_type == cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO - assert math.isclose(response.precise_size_gb, 0.15810000000000002, rel_tol=1e-6) - assert response.deletion_protection_enabled is True - - def test_get_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4255,117 +3828,36 @@ def test_get_cluster_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_get_cluster_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), + transport="rest", ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_get_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_get_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.GetClusterRequest.pb( - cloud_redis_cluster.GetClusterRequest() - ) - 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 = cloud_redis_cluster.Cluster.to_json( - cloud_redis_cluster.Cluster() - ) + # 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 = cloud_redis_cluster.Cluster() - request = cloud_redis_cluster.GetClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.Cluster() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - client.get_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis_cluster.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_get_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.GetClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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.get_cluster(request) - - -def test_get_cluster_rest_flattened(): - client = CloudRedisClusterClient( - 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 = cloud_redis_cluster.Cluster() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/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 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_cluster(**mock_args) + client.get_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -4393,153 +3885,6 @@ def test_get_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_get_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.UpdateClusterRequest, - dict, - ], -) -def test_update_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "size_gb": 739, - "shard_count": 1178, - "psc_configs": [{"network": "network_value"}], - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "psc_config": {}} - ], - "psc_connections": [ - { - "psc_connection_id": "psc_connection_id_value", - "address": "address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - } - ], - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "redis_configs": {}, - "precise_size_gb": 0.15810000000000002, - "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, - "deletion_protection_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis_cluster.UpdateClusterRequest.meta.fields["cluster"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_update_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4676,113 +4021,28 @@ def test_update_cluster_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_update_cluster_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), + transport="rest", ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_update_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_update_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.UpdateClusterRequest.pb( - cloud_redis_cluster.UpdateClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = cloud_redis_cluster.UpdateClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } - client.update_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + cluster=cloud_redis_cluster.Cluster(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.UpdateClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/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.update_cluster(request) - - -def test_update_cluster_rest_flattened(): - client = CloudRedisClusterClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - cluster=cloud_redis_cluster.Cluster(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -4820,47 +4080,6 @@ def test_update_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_update_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.DeleteClusterRequest, - dict, - ], -) -def test_delete_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4983,89 +4202,6 @@ def test_delete_cluster_rest_unset_required_fields(): assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_delete_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_delete_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.DeleteClusterRequest.pb( - cloud_redis_cluster.DeleteClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis_cluster.DeleteClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.DeleteClusterRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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.delete_cluster(request) - - def test_delete_cluster_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5121,179 +4257,34 @@ def test_delete_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_delete_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.CreateClusterRequest, - dict, - ], -) -def test_create_cluster_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.create_cluster in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "size_gb": 739, - "shard_count": 1178, - "psc_configs": [{"network": "network_value"}], - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "psc_config": {}} - ], - "psc_connections": [ - { - "psc_connection_id": "psc_connection_id_value", - "address": "address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - } - ], - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "redis_configs": {}, - "precise_size_gb": 0.15810000000000002, - "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, - "deletion_protection_enabled": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis_cluster.CreateClusterRequest.meta.fields["cluster"] + request = {} + client.create_cluster(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_cluster(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - - request = {} - client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 # Operation methods build a cached wrapper on first rpc call # subsequent calls should use the cached wrapper @@ -5421,89 +4412,6 @@ def test_create_cluster_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "post_create_cluster" - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, "pre_create_cluster" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.CreateClusterRequest.pb( - cloud_redis_cluster.CreateClusterRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis_cluster.CreateClusterRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_cluster( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_cluster_rest_bad_request( - transport: str = "rest", request_type=cloud_redis_cluster.CreateClusterRequest -): - client = CloudRedisClusterClient( - 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.create_cluster(request) - - def test_create_cluster_rest_flattened(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5563,54 +4471,6 @@ def test_create_cluster_rest_flattened_error(transport: str = "rest"): ) -def test_create_cluster_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis_cluster.GetClusterCertificateAuthorityRequest, - dict, - ], -) -def test_get_cluster_certificate_authority_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" - } - 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 = cloud_redis_cluster.CertificateAuthority( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis_cluster.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_cluster_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis_cluster.CertificateAuthority) - assert response.name == "name_value" - - def test_get_cluster_certificate_authority_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5737,96 +4597,10 @@ def test_get_cluster_certificate_authority_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.CloudRedisClusterRestTransport( +def test_get_cluster_certificate_authority_rest_flattened(): + client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisClusterRestInterceptor(), - ) - client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, - "post_get_cluster_certificate_authority", - ) as post, mock.patch.object( - transports.CloudRedisClusterRestInterceptor, - "pre_get_cluster_certificate_authority", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( - cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - ) - 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 = cloud_redis_cluster.CertificateAuthority.to_json( - cloud_redis_cluster.CertificateAuthority() - ) - - request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis_cluster.CertificateAuthority() - - client.get_cluster_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_cluster_certificate_authority_rest_bad_request( - transport: str = "rest", - request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" - } - 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_cluster_certificate_authority(request) - - -def test_get_cluster_certificate_authority_rest_flattened(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5884,12 +4658,6 @@ def test_get_cluster_certificate_authority_rest_flattened_error( ) -def test_get_cluster_certificate_authority_rest_error(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudRedisClusterGrpcTransport( @@ -5982,1065 +4750,2462 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CloudRedisClusterClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = CloudRedisClusterClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.CloudRedisClusterGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_clusters_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + call.return_value = cloud_redis_cluster.ListClustersResponse() + client.list_clusters(request=None) -def test_cloud_redis_cluster_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudRedisClusterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CloudRedisClusterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_clusters", - "get_cluster", - "update_cluster", - "delete_cluster", - "create_cluster", - "get_cluster_certificate_authority", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + call.return_value = cloud_redis_cluster.Cluster() + client.get_cluster(request=None) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + assert args[0] == request_msg -def test_cloud_redis_cluster_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.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisClusterTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_cluster(request=None) -def test_cloud_redis_cluster_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisClusterTransport() - adc.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudRedisClusterClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_cluster(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - transports.CloudRedisClusterRestTransport, - ], -) -def test_cloud_redis_cluster_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CloudRedisClusterGrpcTransport, grpc_helpers), - (transports.CloudRedisClusterGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -def test_cloud_redis_cluster_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_cluster_empty_call_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - create_channel.assert_called_with( - "redis.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="redis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_grpc_transport_client_cert_source_for_mtls( - transport_class, -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_cluster(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() -def test_cloud_redis_cluster_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.CloudRedisClusterRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_cloud_redis_cluster_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_certificate_authority_empty_call_grpc(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + call.return_value = cloud_redis_cluster.CertificateAuthority() + client.get_cluster_certificate_authority(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_cluster_host_no_port(transport_name): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com" + +def test_transport_kind_grpc_asyncio(): + transport = CloudRedisClusterAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) + assert transport.kind == "grpc_asyncio" -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_cluster_host_with_port(transport_name): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com:8000" +def test_initialize_client_w_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) + assert client is not None -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_cloud_redis_cluster_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CloudRedisClusterClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CloudRedisClusterClient( - credentials=creds2, - transport=transport_name, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_clusters_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - session1 = client1.transport.list_clusters._session - session2 = client2.transport.list_clusters._session - assert session1 != session2 - session1 = client1.transport.get_cluster._session - session2 = client2.transport.get_cluster._session - assert session1 != session2 - session1 = client1.transport.update_cluster._session - session2 = client2.transport.update_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_cluster._session - session2 = client2.transport.delete_cluster._session - assert session1 != session2 - session1 = client1.transport.create_cluster._session - session2 = client2.transport.create_cluster._session - assert session1 != session2 - session1 = client1.transport.get_cluster_certificate_authority._session - session2 = client2.transport.get_cluster_certificate_authority._session - assert session1 != session2 + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() -def test_cloud_redis_cluster_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + assert args[0] == request_msg - # Check that channel is used if provided. - transport = transports.CloudRedisClusterGrpcTransport( - host="squid.clam.whelk", - channel=channel, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.Cluster( + name="name_value", + state=cloud_redis_cluster.Cluster.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, + transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, + size_gb=739, + shard_count=1178, + node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, + precise_size_gb=0.15810000000000002, + deletion_protection_enabled=True, + ) + ) + await client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() -def test_cloud_redis_cluster_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + assert args[0] == request_msg - # Check that channel is used if provided. - transport = transports.CloudRedisClusterGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_cluster(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + assert args[0] == request_msg - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisClusterGrpcTransport, - transports.CloudRedisClusterGrpcAsyncIOTransport, - ], -) -def test_cloud_redis_cluster_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - -def test_cloud_redis_cluster_grpc_lro_client(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_cluster_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_cluster(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() + assert args[0] == request_msg -def test_cloud_redis_cluster_grpc_lro_async_client(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_cluster_empty_call_grpc_asyncio(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_cluster(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() + assert args[0] == request_msg -def test_certificate_authority_path(): - project = "squid" - location = "clam" - cluster = "whelk" - expected = "projects/{project}/locations/{location}/clusters/{cluster}/certificateAuthority".format( - project=project, - location=location, - cluster=cluster, - ) - actual = CloudRedisClusterClient.certificate_authority_path( - project, location, cluster + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_cluster_certificate_authority_empty_call_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - assert expected == actual + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis_cluster.CertificateAuthority( + name="name_value", + ) + ) + await client.get_cluster_certificate_authority(request=None) -def test_parse_certificate_authority_path(): - expected = { - "project": "octopus", - "location": "oyster", - "cluster": "nudibranch", - } - path = CloudRedisClusterClient.certificate_authority_path(**expected) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_certificate_authority_path(path) - assert expected == actual + assert args[0] == request_msg -def test_cluster_path(): - project = "cuttlefish" - location = "mussel" - cluster = "winkle" - expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( - project=project, - location=location, - cluster=cluster, +def test_transport_kind_rest(): + transport = CloudRedisClusterClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() ) - actual = CloudRedisClusterClient.cluster_path(project, location, cluster) - assert expected == actual + assert transport.kind == "rest" -def test_parse_cluster_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "cluster": "abalone", - } - path = CloudRedisClusterClient.cluster_path(**expected) +def test_list_clusters_rest_bad_request( + request_type=cloud_redis_cluster.ListClustersRequest, +): + client = CloudRedisClusterClient( + 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) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_cluster_path(path) - assert expected == actual + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_clusters(request) -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.ListClustersRequest, + dict, + ], +) +def test_list_clusters_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = CloudRedisClusterClient.common_billing_account_path(billing_account) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = CloudRedisClusterClient.common_billing_account_path(**expected) + # 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 = cloud_redis_cluster.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_billing_account_path(path) - assert expected == actual + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = cloud_redis_cluster.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_clusters(request) -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = CloudRedisClusterClient.common_folder_path(folder) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = CloudRedisClusterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_folder_path(path) - assert expected == actual +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, "post_list_clusters" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_list_clusters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.ListClustersRequest.pb( + cloud_redis_cluster.ListClustersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = CloudRedisClusterClient.common_organization_path(organization) - assert expected == actual + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.ListClustersResponse.to_json( + cloud_redis_cluster.ListClustersResponse() + ) + req.return_value.content = return_value + request = cloud_redis_cluster.ListClustersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.ListClustersResponse() -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = CloudRedisClusterClient.common_organization_path(**expected) + client.list_clusters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_organization_path(path) - assert expected == actual + pre.assert_called_once() + post.assert_called_once() -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, +def test_get_cluster_rest_bad_request( + request_type=cloud_redis_cluster.GetClusterRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - actual = CloudRedisClusterClient.common_project_path(project) - assert expected == actual + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_cluster(request) -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = CloudRedisClusterClient.common_project_path(**expected) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_project_path(path) - assert expected == actual +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = CloudRedisClusterClient.common_location_path(project, location) - assert expected == actual + # 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 = cloud_redis_cluster.Cluster( + name="name_value", + state=cloud_redis_cluster.Cluster.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH, + transit_encryption_mode=cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED, + size_gb=739, + shard_count=1178, + node_type=cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO, + precise_size_gb=0.15810000000000002, + deletion_protection_enabled=True, + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = CloudRedisClusterClient.common_location_path(**expected) + # Convert return value to protobuf type + return_value = cloud_redis_cluster.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster(request) - # Check that the path construction is reversible. - actual = CloudRedisClusterClient.parse_common_location_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis_cluster.Cluster) + assert response.name == "name_value" + assert response.state == cloud_redis_cluster.Cluster.State.CREATING + assert response.uid == "uid_value" + assert response.replica_count == 1384 + assert ( + response.authorization_mode + == cloud_redis_cluster.AuthorizationMode.AUTH_MODE_IAM_AUTH + ) + assert ( + response.transit_encryption_mode + == cloud_redis_cluster.TransitEncryptionMode.TRANSIT_ENCRYPTION_MODE_DISABLED + ) + assert response.size_gb == 739 + assert response.shard_count == 1178 + assert response.node_type == cloud_redis_cluster.NodeType.REDIS_SHARED_CORE_NANO + assert math.isclose(response.precise_size_gb, 0.15810000000000002, rel_tol=1e-6) + assert response.deletion_protection_enabled is True -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) with mock.patch.object( - transports.CloudRedisClusterTransport, "_prep_wrapped_messages" - ) as prep: - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_get_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_get_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.GetClusterRequest.pb( + cloud_redis_cluster.GetClusterRequest() ) - prep.assert_called_once_with(client_info) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - with mock.patch.object( - transports.CloudRedisClusterTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = CloudRedisClusterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.Cluster.to_json( + cloud_redis_cluster.Cluster() ) - prep.assert_called_once_with(client_info) + req.return_value.content = return_value + request = cloud_redis_cluster.GetClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.Cluster() -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + client.get_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest +def test_update_cluster_rest_bad_request( + request_type=cloud_redis_cluster.UpdateClusterRequest, ): client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_location(request) + client.update_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.UpdateClusterRequest, + dict, + ], +) +def test_update_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "name": "projects/sample1/locations/sample2/clusters/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "size_gb": 739, + "shard_count": 1178, + "psc_configs": [{"network": "network_value"}], + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "psc_config": {}} + ], + "psc_connections": [ + { + "psc_connection_id": "psc_connection_id_value", + "address": "address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + } + ], + "state_info": { + "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} + }, + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "redis_configs": {}, + "precise_size_gb": 0.15810000000000002, + "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, + "deletion_protection_enabled": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis_cluster.UpdateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_update_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_update_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.UpdateClusterRequest.pb( + cloud_redis_cluster.UpdateClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.UpdateClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_cluster_rest_bad_request( + request_type=cloud_redis_cluster.DeleteClusterRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.DeleteClusterRequest, + dict, + ], +) +def test_delete_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_delete_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_delete_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.DeleteClusterRequest.pb( + cloud_redis_cluster.DeleteClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.DeleteClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_cluster_rest_bad_request( + request_type=cloud_redis_cluster.CreateClusterRequest, +): + client = CloudRedisClusterClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "size_gb": 739, + "shard_count": 1178, + "psc_configs": [{"network": "network_value"}], + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "psc_config": {}} + ], + "psc_connections": [ + { + "psc_connection_id": "psc_connection_id_value", + "address": "address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + } + ], + "state_info": { + "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} + }, + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "redis_configs": {}, + "precise_size_gb": 0.15810000000000002, + "zone_distribution_config": {"mode": 1, "zone": "zone_value"}, + "deletion_protection_enabled": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis_cluster.CreateClusterRequest.meta.fields["cluster"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["cluster"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_cluster_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "post_create_cluster" + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, "pre_create_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.CreateClusterRequest.pb( + cloud_redis_cluster.CreateClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis_cluster.CreateClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_certificate_authority_rest_bad_request( + request_type=cloud_redis_cluster.GetClusterCertificateAuthorityRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_cluster_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis_cluster.GetClusterCertificateAuthorityRequest, + dict, + ], +) +def test_get_cluster_certificate_authority_rest_call_success(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/certificateAuthority" + } + 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 = cloud_redis_cluster.CertificateAuthority( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis_cluster.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis_cluster.CertificateAuthority) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CloudRedisClusterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisClusterRestInterceptor(), + ) + client = CloudRedisClusterClient(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.CloudRedisClusterRestInterceptor, + "post_get_cluster_certificate_authority", + ) as post, mock.patch.object( + transports.CloudRedisClusterRestInterceptor, + "pre_get_cluster_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis_cluster.GetClusterCertificateAuthorityRequest.pb( + cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis_cluster.CertificateAuthority.to_json( + cloud_redis_cluster.CertificateAuthority() + ) + req.return_value.content = return_value + + request = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis_cluster.CertificateAuthority() + + client.get_cluster_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_clusters_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_clusters), "__call__") as call: + client.list_clusters(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.ListClustersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_cluster), "__call__") as call: + client.get_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_cluster), "__call__") as call: + client.update_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.UpdateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_cluster), "__call__") as call: + client.delete_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.DeleteClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_cluster_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_cluster), "__call__") as call: + client.create_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.CreateClusterRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_cluster_certificate_authority_empty_call_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_cluster_certificate_authority), "__call__" + ) as call: + client.get_cluster_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis_cluster.GetClusterCertificateAuthorityRequest() + + assert args[0] == request_msg + + +def test_cloud_redis_cluster_rest_lro_client(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudRedisClusterGrpcTransport, + ) + + +def test_cloud_redis_cluster_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudRedisClusterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_redis_cluster_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudRedisClusterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_clusters", + "get_cluster", + "update_cluster", + "delete_cluster", + "create_cluster", + "get_cluster_certificate_authority", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_redis_cluster_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.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisClusterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_redis_cluster_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.redis_cluster_v1beta1.services.cloud_redis_cluster.transports.CloudRedisClusterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisClusterTransport() + adc.assert_called_once() + + +def test_cloud_redis_cluster_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudRedisClusterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + transports.CloudRedisClusterRestTransport, + ], +) +def test_cloud_redis_cluster_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudRedisClusterGrpcTransport, grpc_helpers), + (transports.CloudRedisClusterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_redis_cluster_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "redis.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="redis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_redis_cluster_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.CloudRedisClusterRestTransport( + 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_cloud_redis_cluster_host_no_port(transport_name): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "redis.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_redis_cluster_host_with_port(transport_name): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "redis.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_redis_cluster_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudRedisClusterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudRedisClusterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_clusters._session + session2 = client2.transport.list_clusters._session + assert session1 != session2 + session1 = client1.transport.get_cluster._session + session2 = client2.transport.get_cluster._session + assert session1 != session2 + session1 = client1.transport.update_cluster._session + session2 = client2.transport.update_cluster._session + assert session1 != session2 + session1 = client1.transport.delete_cluster._session + session2 = client2.transport.delete_cluster._session + assert session1 != session2 + session1 = client1.transport.create_cluster._session + session2 = client2.transport.create_cluster._session + assert session1 != session2 + session1 = client1.transport.get_cluster_certificate_authority._session + session2 = client2.transport.get_cluster_certificate_authority._session + assert session1 != session2 + + +def test_cloud_redis_cluster_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudRedisClusterGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_redis_cluster_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudRedisClusterGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_cluster_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "request_type", + "transport_class", [ - locations_pb2.GetLocationRequest, - dict, + transports.CloudRedisClusterGrpcTransport, + transports.CloudRedisClusterGrpcAsyncIOTransport, ], ) -def test_get_location_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_cloud_redis_cluster_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() - response = client.get_location(request) + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): +def test_cloud_redis_cluster_grpc_lro_client(): client = CloudRedisClusterClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) - - # 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.list_locations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], -) -def test_list_locations_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_locations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): - client = CloudRedisClusterClient( +def test_cloud_redis_cluster_grpc_lro_async_client(): + client = CloudRedisClusterAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc_asyncio", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, ) - # 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.cancel_operation(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_certificate_authority_path(): + project = "squid" + location = "clam" + cluster = "whelk" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/certificateAuthority".format( + project=project, + location=location, + cluster=cluster, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + actual = CloudRedisClusterClient.certificate_authority_path( + project, location, cluster + ) + assert expected == actual - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_parse_certificate_authority_path(): + expected = { + "project": "octopus", + "location": "oyster", + "cluster": "nudibranch", + } + path = CloudRedisClusterClient.certificate_authority_path(**expected) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_certificate_authority_path(path) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_cluster_path(): + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( + project=project, + location=location, + cluster=cluster, ) - - # 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.delete_operation(request) + actual = CloudRedisClusterClient.cluster_path(project, location, cluster) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_cluster_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", + } + path = CloudRedisClusterClient.cluster_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_cluster_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudRedisClusterClient.common_billing_account_path(billing_account) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = CloudRedisClusterClient.common_billing_account_path(**expected) -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_billing_account_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, ) + actual = CloudRedisClusterClient.common_folder_path(folder) + assert expected == actual - # 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_operation(request) +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = CloudRedisClusterClient.common_folder_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_folder_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudRedisClusterClient.common_organization_path(organization) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = CloudRedisClusterClient.common_organization_path(**expected) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_organization_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, ) + actual = CloudRedisClusterClient.common_project_path(project) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = CloudRedisClusterClient.common_project_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + actual = CloudRedisClusterClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = CloudRedisClusterClient.common_location_path(**expected) - response = client.list_operations(request) + # Check that the path construction is reversible. + actual = CloudRedisClusterClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudRedisClusterTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudRedisClusterTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudRedisClusterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -7070,7 +7235,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7123,7 +7288,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7168,7 +7333,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -7209,7 +7374,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7262,7 +7427,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7307,7 +7472,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -7348,7 +7513,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7403,7 +7568,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7450,7 +7615,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -7493,7 +7658,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7548,7 +7713,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7595,7 +7760,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -7638,7 +7803,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7693,7 +7858,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7740,7 +7905,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -7783,7 +7948,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7835,9 +8000,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials() - ) + client = CloudRedisClusterAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -7883,7 +8046,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = CloudRedisClusterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -7899,22 +8062,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CloudRedisClusterClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CloudRedisClusterAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CloudRedisClusterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/async_client.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/async_client.py index 9c787522344f..2d8f440212ec 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/async_client.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/async_client.py @@ -1805,11 +1805,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1862,11 +1858,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1923,11 +1915,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1980,11 +1968,7 @@ async def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2034,11 +2018,7 @@ async def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -2091,11 +2071,7 @@ async def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/client.py index 7ad754255344..79f73b788274 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -2209,11 +2209,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2266,11 +2262,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2327,11 +2319,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2384,11 +2372,7 @@ def cancel_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2438,11 +2422,7 @@ def get_location( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_location] # Certain fields should be provided within the metadata header; # add these here. @@ -2495,11 +2475,7 @@ def list_locations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_locations] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/README.rst b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/README.rst new file mode 100644 index 000000000000..fce41822b52c --- /dev/null +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CloudRedisTransport` is the ABC for all transports. +- public child `CloudRedisGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CloudRedisGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCloudRedisRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CloudRedisRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 4276a2789f6f..0f62d5e68617 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -185,6 +185,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py index 9ea174e17262..80737763497f 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -249,6 +250,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -635,66 +639,105 @@ def reschedule_maintenance( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=600.0, client_info=client_info, ), - self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=600.0, client_info=client_info, ), - self.get_instance_auth_string: gapic_v1.method_async.wrap_method( + self.get_instance_auth_string: self._wrap_method( self.get_instance_auth_string, default_timeout=600.0, client_info=client_info, ), - self.create_instance: gapic_v1.method_async.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, client_info=client_info, ), - self.update_instance: gapic_v1.method_async.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=600.0, client_info=client_info, ), - self.upgrade_instance: gapic_v1.method_async.wrap_method( + self.upgrade_instance: self._wrap_method( self.upgrade_instance, default_timeout=600.0, client_info=client_info, ), - self.import_instance: gapic_v1.method_async.wrap_method( + self.import_instance: self._wrap_method( self.import_instance, default_timeout=600.0, client_info=client_info, ), - self.export_instance: gapic_v1.method_async.wrap_method( + self.export_instance: self._wrap_method( self.export_instance, default_timeout=600.0, client_info=client_info, ), - self.failover_instance: gapic_v1.method_async.wrap_method( + self.failover_instance: self._wrap_method( self.failover_instance, default_timeout=600.0, client_info=client_info, ), - self.delete_instance: gapic_v1.method_async.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, ), - self.reschedule_maintenance: gapic_v1.method_async.wrap_method( + self.reschedule_maintenance: self._wrap_method( self.reschedule_maintenance, default_timeout=600.0, client_info=client_info, ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py index 0290c2121a42..6aa6bdb221e5 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.redis_v1.types import cloud_redis + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCloudRedisRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.redis_v1.types import cloud_redis - -from .base import CloudRedisTransport -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, @@ -559,8 +549,8 @@ class CloudRedisRestStub: _interceptor: CloudRedisRestInterceptor -class CloudRedisRestTransport(CloudRedisTransport): - """REST backend transport for CloudRedis. +class CloudRedisRestTransport(_BaseCloudRedisRestTransport): + """REST backend synchronous transport for CloudRedis. Configures and manages Cloud Memorystore for Redis instances @@ -589,7 +579,6 @@ class CloudRedisRestTransport(CloudRedisTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -643,21 +632,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -721,21 +701,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateInstance(CloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("CreateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "instanceId": "", - } - - @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 - } + return hash("CloudRedisRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -765,45 +758,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/instances", - "body": "instance", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - pb_request = cloud_redis.CreateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -817,19 +801,33 @@ def __call__( resp = self._interceptor.post_create_instance(resp) return resp - class _DeleteInstance(CloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("DeleteInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -859,38 +857,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - pb_request = cloud_redis.DeleteInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -904,19 +893,34 @@ def __call__( resp = self._interceptor.post_delete_instance(resp) return resp - class _ExportInstance(CloudRedisRestStub): + class _ExportInstance( + _BaseCloudRedisRestTransport._BaseExportInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("ExportInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ExportInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -946,45 +950,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:export", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_export_instance(request, metadata) - pb_request = cloud_redis.ExportInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._ExportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -998,19 +993,34 @@ def __call__( resp = self._interceptor.post_export_instance(resp) return resp - class _FailoverInstance(CloudRedisRestStub): + class _FailoverInstance( + _BaseCloudRedisRestTransport._BaseFailoverInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("FailoverInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.FailoverInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1040,47 +1050,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:failover", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + ) request, metadata = self._interceptor.pre_failover_instance( request, metadata ) - pb_request = cloud_redis.FailoverInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._FailoverInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1094,19 +1091,33 @@ def __call__( resp = self._interceptor.post_failover_instance(resp) return resp - class _GetInstance(CloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("GetInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1133,38 +1144,31 @@ def __call__( A Memorystore for Redis instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - pb_request = cloud_redis.GetInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1180,19 +1184,33 @@ def __call__( resp = self._interceptor.post_get_instance(resp) return resp - class _GetInstanceAuthString(CloudRedisRestStub): + class _GetInstanceAuthString( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString, CloudRedisRestStub + ): def __hash__(self): - return hash("GetInstanceAuthString") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.GetInstanceAuthString") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1219,40 +1237,29 @@ def __call__( Instance AUTH string details. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/instances/*}/authString", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance_auth_string( request, metadata ) - pb_request = cloud_redis.GetInstanceAuthStringRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._GetInstanceAuthString._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1268,19 +1275,34 @@ def __call__( resp = self._interceptor.post_get_instance_auth_string(resp) return resp - class _ImportInstance(CloudRedisRestStub): + class _ImportInstance( + _BaseCloudRedisRestTransport._BaseImportInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("ImportInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ImportInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1310,45 +1332,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:import", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_import_instance(request, metadata) - pb_request = cloud_redis.ImportInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._ImportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1362,19 +1375,33 @@ def __call__( resp = self._interceptor.post_import_instance(resp) return resp - class _ListInstances(CloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub + ): def __hash__(self): - return hash("ListInstances") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1403,38 +1430,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/instances", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - pb_request = cloud_redis.ListInstancesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1450,19 +1470,34 @@ def __call__( resp = self._interceptor.post_list_instances(resp) return resp - class _RescheduleMaintenance(CloudRedisRestStub): + class _RescheduleMaintenance( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance, CloudRedisRestStub + ): def __hash__(self): - return hash("RescheduleMaintenance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.RescheduleMaintenance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1492,47 +1527,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + ) request, metadata = self._interceptor.pre_reschedule_maintenance( request, metadata ) - pb_request = cloud_redis.RescheduleMaintenanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._RescheduleMaintenance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1546,21 +1568,34 @@ def __call__( resp = self._interceptor.post_reschedule_maintenance(resp) return resp - class _UpdateInstance(CloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("UpdateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CloudRedisRestTransport.UpdateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1590,45 +1625,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{instance.name=projects/*/locations/*/instances/*}", - "body": "instance", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - pb_request = cloud_redis.UpdateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1642,19 +1668,34 @@ def __call__( resp = self._interceptor.post_update_instance(resp) return resp - class _UpgradeInstance(CloudRedisRestStub): + class _UpgradeInstance( + _BaseCloudRedisRestTransport._BaseUpgradeInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("UpgradeInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.UpgradeInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1684,47 +1725,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/instances/*}:upgrade", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + ) request, metadata = self._interceptor.pre_upgrade_instance( request, metadata ) - pb_request = cloud_redis.UpgradeInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._UpgradeInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1834,7 +1862,34 @@ def upgrade_instance( def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(CloudRedisRestStub): + class _GetLocation( + _BaseCloudRedisRestTransport._BaseGetLocation, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.GetLocationRequest, @@ -1858,32 +1913,31 @@ def __call__( locations_pb2.Location: Response from GetLocation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = CloudRedisRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1891,8 +1945,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) return resp @@ -1900,7 +1955,34 @@ def __call__( def list_locations(self): return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(CloudRedisRestStub): + class _ListLocations( + _BaseCloudRedisRestTransport._BaseListLocations, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: locations_pb2.ListLocationsRequest, @@ -1924,32 +2006,31 @@ def __call__( locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*}/locations", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseCloudRedisRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = CloudRedisRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1957,8 +2038,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) return resp @@ -1966,7 +2048,34 @@ def __call__( def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(CloudRedisRestStub): + class _CancelOperation( + _BaseCloudRedisRestTransport._BaseCancelOperation, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.CancelOperationRequest, @@ -1987,34 +2096,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseCancelOperation._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2028,7 +2132,34 @@ def __call__( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(CloudRedisRestStub): + class _DeleteOperation( + _BaseCloudRedisRestTransport._BaseDeleteOperation, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -2049,34 +2180,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCloudRedisRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CloudRedisRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2090,7 +2216,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CloudRedisRestStub): + class _GetOperation( + _BaseCloudRedisRestTransport._BaseGetOperation, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -2114,32 +2267,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseCloudRedisRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = CloudRedisRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2147,8 +2299,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -2156,7 +2309,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CloudRedisRestStub): + class _ListOperations( + _BaseCloudRedisRestTransport._BaseListOperations, CloudRedisRestStub + ): + def __hash__(self): + return hash("CloudRedisRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -2180,32 +2360,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseCloudRedisRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = CloudRedisRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2213,8 +2390,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py new file mode 100644 index 000000000000..0f262910c031 --- /dev/null +++ b/packages/google-cloud-redis/google/cloud/redis_v1/services/cloud_redis/transports/rest_base.py @@ -0,0 +1,834 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.redis_v1.types import cloud_redis + +from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport + + +class _BaseCloudRedisRestTransport(CloudRedisTransport): + """Base REST backend transport for CloudRedis. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ExportInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseExportInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFailoverInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:failover", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.FailoverInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstanceAuthString: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*}/authString", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.GetInstanceAuthStringRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ImportInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseImportInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRescheduleMaintenance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.RescheduleMaintenanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.UpdateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpgradeInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*}:upgrade", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.UpgradeInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCloudRedisRestTransport",) diff --git a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/README.rst b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/README.rst new file mode 100644 index 000000000000..fce41822b52c --- /dev/null +++ b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CloudRedisTransport` is the ABC for all transports. +- public child `CloudRedisGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CloudRedisGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCloudRedisRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CloudRedisRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/grpc_asyncio.py b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/grpc_asyncio.py index 7b2abb75cc14..03281c8cb333 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/grpc_asyncio.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -248,6 +249,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -634,65 +638,74 @@ def reschedule_maintenance( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_instances: gapic_v1.method_async.wrap_method( + self.list_instances: self._wrap_method( self.list_instances, default_timeout=600.0, client_info=client_info, ), - self.get_instance: gapic_v1.method_async.wrap_method( + self.get_instance: self._wrap_method( self.get_instance, default_timeout=600.0, client_info=client_info, ), - self.get_instance_auth_string: gapic_v1.method_async.wrap_method( + self.get_instance_auth_string: self._wrap_method( self.get_instance_auth_string, default_timeout=600.0, client_info=client_info, ), - self.create_instance: gapic_v1.method_async.wrap_method( + self.create_instance: self._wrap_method( self.create_instance, default_timeout=600.0, client_info=client_info, ), - self.update_instance: gapic_v1.method_async.wrap_method( + self.update_instance: self._wrap_method( self.update_instance, default_timeout=600.0, client_info=client_info, ), - self.upgrade_instance: gapic_v1.method_async.wrap_method( + self.upgrade_instance: self._wrap_method( self.upgrade_instance, default_timeout=600.0, client_info=client_info, ), - self.import_instance: gapic_v1.method_async.wrap_method( + self.import_instance: self._wrap_method( self.import_instance, default_timeout=600.0, client_info=client_info, ), - self.export_instance: gapic_v1.method_async.wrap_method( + self.export_instance: self._wrap_method( self.export_instance, default_timeout=600.0, client_info=client_info, ), - self.failover_instance: gapic_v1.method_async.wrap_method( + self.failover_instance: self._wrap_method( self.failover_instance, default_timeout=600.0, client_info=client_info, ), - self.delete_instance: gapic_v1.method_async.wrap_method( + self.delete_instance: self._wrap_method( self.delete_instance, default_timeout=600.0, client_info=client_info, ), - self.reschedule_maintenance: gapic_v1.method_async.wrap_method( + self.reschedule_maintenance: self._wrap_method( self.reschedule_maintenance, default_timeout=None, client_info=client_info, ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("CloudRedisGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest.py b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest.py index c24235f2dad1..6854beb9973e 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest.py @@ -16,39 +16,29 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.redis_v1beta1.types import cloud_redis + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCloudRedisRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.redis_v1beta1.types import cloud_redis - -from .base import CloudRedisTransport -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, @@ -424,8 +414,8 @@ class CloudRedisRestStub: _interceptor: CloudRedisRestInterceptor -class CloudRedisRestTransport(CloudRedisTransport): - """REST backend transport for CloudRedis. +class CloudRedisRestTransport(_BaseCloudRedisRestTransport): + """REST backend synchronous transport for CloudRedis. Configures and manages Cloud Memorystore for Redis instances @@ -454,7 +444,6 @@ class CloudRedisRestTransport(CloudRedisTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -508,21 +497,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -586,21 +566,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateInstance(CloudRedisRestStub): + class _CreateInstance( + _BaseCloudRedisRestTransport._BaseCreateInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("CreateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "instanceId": "", - } - - @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 - } + return hash("CloudRedisRestTransport.CreateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -630,45 +623,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{parent=projects/*/locations/*}/instances", - "body": "instance", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_create_instance(request, metadata) - pb_request = cloud_redis.CreateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -682,19 +666,33 @@ def __call__( resp = self._interceptor.post_create_instance(resp) return resp - class _DeleteInstance(CloudRedisRestStub): + class _DeleteInstance( + _BaseCloudRedisRestTransport._BaseDeleteInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("DeleteInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.DeleteInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -724,38 +722,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_http_options() + ) request, metadata = self._interceptor.pre_delete_instance(request, metadata) - pb_request = cloud_redis.DeleteInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._DeleteInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -769,19 +758,34 @@ def __call__( resp = self._interceptor.post_delete_instance(resp) return resp - class _ExportInstance(CloudRedisRestStub): + class _ExportInstance( + _BaseCloudRedisRestTransport._BaseExportInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("ExportInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ExportInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -811,45 +815,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:export", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_export_instance(request, metadata) - pb_request = cloud_redis.ExportInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseExportInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseExportInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._ExportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -863,19 +858,34 @@ def __call__( resp = self._interceptor.post_export_instance(resp) return resp - class _FailoverInstance(CloudRedisRestStub): + class _FailoverInstance( + _BaseCloudRedisRestTransport._BaseFailoverInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("FailoverInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.FailoverInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -905,47 +915,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:failover", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_http_options() + ) request, metadata = self._interceptor.pre_failover_instance( request, metadata ) - pb_request = cloud_redis.FailoverInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseFailoverInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._FailoverInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,19 +956,33 @@ def __call__( resp = self._interceptor.post_failover_instance(resp) return resp - class _GetInstance(CloudRedisRestStub): + class _GetInstance( + _BaseCloudRedisRestTransport._BaseGetInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("GetInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.GetInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -998,38 +1009,31 @@ def __call__( A Memorystore for Redis instance. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance(request, metadata) - pb_request = cloud_redis.GetInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseGetInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._GetInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1045,19 +1049,33 @@ def __call__( resp = self._interceptor.post_get_instance(resp) return resp - class _GetInstanceAuthString(CloudRedisRestStub): + class _GetInstanceAuthString( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString, CloudRedisRestStub + ): def __hash__(self): - return hash("GetInstanceAuthString") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.GetInstanceAuthString") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1084,40 +1102,29 @@ def __call__( Instance AUTH string details. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}/authString", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_http_options() + ) request, metadata = self._interceptor.pre_get_instance_auth_string( request, metadata ) - pb_request = cloud_redis.GetInstanceAuthStringRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._GetInstanceAuthString._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1133,19 +1140,34 @@ def __call__( resp = self._interceptor.post_get_instance_auth_string(resp) return resp - class _ImportInstance(CloudRedisRestStub): + class _ImportInstance( + _BaseCloudRedisRestTransport._BaseImportInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("ImportInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ImportInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1175,45 +1197,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:import", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_http_options() + ) request, metadata = self._interceptor.pre_import_instance(request, metadata) - pb_request = cloud_redis.ImportInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseImportInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseImportInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._ImportInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1227,19 +1240,33 @@ def __call__( resp = self._interceptor.post_import_instance(resp) return resp - class _ListInstances(CloudRedisRestStub): + class _ListInstances( + _BaseCloudRedisRestTransport._BaseListInstances, CloudRedisRestStub + ): def __hash__(self): - return hash("ListInstances") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.ListInstances") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1268,38 +1295,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1beta1/{parent=projects/*/locations/*}/instances", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_http_options() + ) request, metadata = self._interceptor.pre_list_instances(request, metadata) - pb_request = cloud_redis.ListInstancesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseListInstances._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CloudRedisRestTransport._ListInstances._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1315,19 +1335,34 @@ def __call__( resp = self._interceptor.post_list_instances(resp) return resp - class _RescheduleMaintenance(CloudRedisRestStub): + class _RescheduleMaintenance( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance, CloudRedisRestStub + ): def __hash__(self): - return hash("RescheduleMaintenance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.RescheduleMaintenance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1357,47 +1392,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_http_options() + ) request, metadata = self._interceptor.pre_reschedule_maintenance( request, metadata ) - pb_request = cloud_redis.RescheduleMaintenanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._RescheduleMaintenance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1411,21 +1433,34 @@ def __call__( resp = self._interceptor.post_reschedule_maintenance(resp) return resp - class _UpdateInstance(CloudRedisRestStub): + class _UpdateInstance( + _BaseCloudRedisRestTransport._BaseUpdateInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("UpdateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("CloudRedisRestTransport.UpdateInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1455,45 +1490,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1beta1/{instance.name=projects/*/locations/*/instances/*}", - "body": "instance", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_http_options() + ) request, metadata = self._interceptor.pre_update_instance(request, metadata) - pb_request = cloud_redis.UpdateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseUpdateInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._UpdateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1507,19 +1533,34 @@ def __call__( resp = self._interceptor.post_update_instance(resp) return resp - class _UpgradeInstance(CloudRedisRestStub): + class _UpgradeInstance( + _BaseCloudRedisRestTransport._BaseUpgradeInstance, CloudRedisRestStub + ): def __hash__(self): - return hash("UpgradeInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CloudRedisRestTransport.UpgradeInstance") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1549,47 +1590,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:upgrade", - "body": "*", - }, - ] + http_options = ( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_http_options() + ) request, metadata = self._interceptor.pre_upgrade_instance( request, metadata ) - pb_request = cloud_redis.UpgradeInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CloudRedisRestTransport._UpgradeInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest_base.py b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest_base.py new file mode 100644 index 000000000000..e5478cb85259 --- /dev/null +++ b/packages/google-cloud-redis/google/cloud/redis_v1beta1/services/cloud_redis/transports/rest_base.py @@ -0,0 +1,683 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.redis_v1beta1.types import cloud_redis + +from .base import DEFAULT_CLIENT_INFO, CloudRedisTransport + + +class _BaseCloudRedisRestTransport(CloudRedisTransport): + """Base REST backend transport for CloudRedis. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "redis.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'redis.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseCreateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseDeleteInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ExportInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseExportInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFailoverInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:failover", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.FailoverInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseFailoverInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstanceAuthString: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}/authString", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.GetInstanceAuthStringRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseGetInstanceAuthString._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ImportInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseImportInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRescheduleMaintenance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.RescheduleMaintenanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseRescheduleMaintenance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.UpdateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseUpdateInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpgradeInstance: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/instances/*}:upgrade", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cloud_redis.UpgradeInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCloudRedisRestTransport._BaseUpgradeInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseCloudRedisRestTransport",) diff --git a/packages/google-cloud-redis/setup.py b/packages/google-cloud-redis/setup.py index 2b8409ddb58b..264752c1ca33 100644 --- a/packages/google-cloud-redis/setup.py +++ b/packages/google-cloud-redis/setup.py @@ -46,6 +46,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -88,6 +89,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/google-cloud-redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index c190120c175a..af21a959a30f 100644 --- a/packages/google-cloud-redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/google-cloud-redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,17 +65,9 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_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.type import dayofweek_pb2 # type: ignore from google.type import timeofday_pb2 # type: ignore -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.redis_v1.services.cloud_redis import ( CloudRedisAsyncClient, @@ -69,10 +78,24 @@ from google.cloud.redis_v1.types import cloud_redis +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1131,25 +1154,6 @@ def test_list_instances(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_instances_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ListInstancesRequest() - - def test_list_instances_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1215,30 +1219,6 @@ def test_list_instances_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_instances_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ListInstancesRequest() - - @pytest.mark.asyncio async def test_list_instances_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1247,7 +1227,7 @@ async def test_list_instances_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1286,7 +1266,7 @@ async def test_list_instances_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ListInstancesRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1354,7 +1334,7 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1424,7 +1404,7 @@ def test_list_instances_flattened_error(): @pytest.mark.asyncio async def test_list_instances_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1453,7 +1433,7 @@ async def test_list_instances_flattened_async(): @pytest.mark.asyncio async def test_list_instances_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1563,7 +1543,7 @@ def test_list_instances_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_instances_async_pager(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1613,7 +1593,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1759,25 +1739,6 @@ def test_get_instance(request_type, transport: str = "grpc"): ] -def test_get_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceRequest() - - def test_get_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1841,57 +1802,6 @@ def test_get_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.Instance( - name="name_value", - display_name="display_name_value", - location_id="location_id_value", - alternative_location_id="alternative_location_id_value", - redis_version="redis_version_value", - reserved_ip_range="reserved_ip_range_value", - secondary_ip_range="secondary_ip_range_value", - host="host_value", - port=453, - current_location_id="current_location_id_value", - state=cloud_redis.Instance.State.CREATING, - status_message="status_message_value", - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network="authorized_network_value", - persistence_iam_identity="persistence_iam_identity_value", - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint="read_endpoint_value", - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - customer_managed_key="customer_managed_key_value", - suspension_reasons=[ - cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE - ], - maintenance_version="maintenance_version_value", - available_maintenance_versions=["available_maintenance_versions_value"], - ) - ) - response = await client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceRequest() - - @pytest.mark.asyncio async def test_get_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1900,7 +1810,7 @@ async def test_get_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1939,7 +1849,7 @@ async def test_get_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.GetInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2069,7 +1979,7 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2139,7 +2049,7 @@ def test_get_instance_flattened_error(): @pytest.mark.asyncio async def test_get_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2168,7 +2078,7 @@ async def test_get_instance_flattened_async(): @pytest.mark.asyncio async def test_get_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2218,27 +2128,6 @@ def test_get_instance_auth_string(request_type, transport: str = "grpc"): assert response.auth_string == "auth_string_value" -def test_get_instance_auth_string_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance_auth_string() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceAuthStringRequest() - - def test_get_instance_auth_string_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2309,31 +2198,6 @@ def test_get_instance_auth_string_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_auth_string_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.InstanceAuthString( - auth_string="auth_string_value", - ) - ) - response = await client.get_instance_auth_string() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceAuthStringRequest() - - @pytest.mark.asyncio async def test_get_instance_auth_string_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2342,7 +2206,7 @@ async def test_get_instance_auth_string_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2382,7 +2246,7 @@ async def test_get_instance_auth_string_async( request_type=cloud_redis.GetInstanceAuthStringRequest, ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2452,7 +2316,7 @@ def test_get_instance_auth_string_field_headers(): @pytest.mark.asyncio async def test_get_instance_auth_string_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2526,7 +2390,7 @@ def test_get_instance_auth_string_flattened_error(): @pytest.mark.asyncio async def test_get_instance_auth_string_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2557,7 +2421,7 @@ async def test_get_instance_auth_string_flattened_async(): @pytest.mark.asyncio async def test_get_instance_auth_string_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2602,25 +2466,6 @@ def test_create_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.CreateInstanceRequest() - - def test_create_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2691,27 +2536,6 @@ def test_create_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.CreateInstanceRequest() - - @pytest.mark.asyncio async def test_create_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2720,7 +2544,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2764,7 +2588,7 @@ async def test_create_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.CreateInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2827,7 +2651,7 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio async def test_create_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2907,7 +2731,7 @@ def test_create_instance_flattened_error(): @pytest.mark.asyncio async def test_create_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2944,7 +2768,7 @@ async def test_create_instance_flattened_async(): @pytest.mark.asyncio async def test_create_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2991,25 +2815,6 @@ def test_update_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpdateInstanceRequest() - - def test_update_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3074,27 +2879,6 @@ def test_update_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpdateInstanceRequest() - - @pytest.mark.asyncio async def test_update_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3103,7 +2887,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3147,7 +2931,7 @@ async def test_update_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.UpdateInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3210,7 +2994,7 @@ def test_update_instance_field_headers(): @pytest.mark.asyncio async def test_update_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3285,7 +3069,7 @@ def test_update_instance_flattened_error(): @pytest.mark.asyncio async def test_update_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3318,7 +3102,7 @@ async def test_update_instance_flattened_async(): @pytest.mark.asyncio async def test_update_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3364,47 +3148,28 @@ def test_upgrade_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_upgrade_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_upgrade_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = cloud_redis.UpgradeInstanceRequest( + name="name_value", + redis_version="redis_version_value", + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.upgrade_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpgradeInstanceRequest() - - -def test_upgrade_instance_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = cloud_redis.UpgradeInstanceRequest( - name="name_value", - redis_version="redis_version_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.upgrade_instance(request=request) + client.upgrade_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == cloud_redis.UpgradeInstanceRequest( @@ -3455,27 +3220,6 @@ def test_upgrade_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_upgrade_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.upgrade_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpgradeInstanceRequest() - - @pytest.mark.asyncio async def test_upgrade_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3484,7 +3228,7 @@ async def test_upgrade_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3528,7 +3272,7 @@ async def test_upgrade_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.UpgradeInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3591,7 +3335,7 @@ def test_upgrade_instance_field_headers(): @pytest.mark.asyncio async def test_upgrade_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3666,7 +3410,7 @@ def test_upgrade_instance_flattened_error(): @pytest.mark.asyncio async def test_upgrade_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3699,7 +3443,7 @@ async def test_upgrade_instance_flattened_async(): @pytest.mark.asyncio async def test_upgrade_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3745,25 +3489,6 @@ def test_import_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ImportInstanceRequest() - - def test_import_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3832,27 +3557,6 @@ def test_import_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ImportInstanceRequest() - - @pytest.mark.asyncio async def test_import_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3861,7 +3565,7 @@ async def test_import_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3905,7 +3609,7 @@ async def test_import_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ImportInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3968,7 +3672,7 @@ def test_import_instance_field_headers(): @pytest.mark.asyncio async def test_import_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4049,7 +3753,7 @@ def test_import_instance_flattened_error(): @pytest.mark.asyncio async def test_import_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4086,7 +3790,7 @@ async def test_import_instance_flattened_async(): @pytest.mark.asyncio async def test_import_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4134,25 +3838,6 @@ def test_export_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ExportInstanceRequest() - - def test_export_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4221,27 +3906,6 @@ def test_export_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ExportInstanceRequest() - - @pytest.mark.asyncio async def test_export_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4250,7 +3914,7 @@ async def test_export_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4294,7 +3958,7 @@ async def test_export_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ExportInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4357,7 +4021,7 @@ def test_export_instance_field_headers(): @pytest.mark.asyncio async def test_export_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4438,7 +4102,7 @@ def test_export_instance_flattened_error(): @pytest.mark.asyncio async def test_export_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4475,7 +4139,7 @@ async def test_export_instance_flattened_async(): @pytest.mark.asyncio async def test_export_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4525,27 +4189,6 @@ def test_failover_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_failover_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.failover_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.FailoverInstanceRequest() - - def test_failover_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4618,29 +4261,6 @@ def test_failover_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_failover_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.failover_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.FailoverInstanceRequest() - - @pytest.mark.asyncio async def test_failover_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4649,7 +4269,7 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4693,7 +4313,7 @@ async def test_failover_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.FailoverInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4760,7 +4380,7 @@ def test_failover_instance_field_headers(): @pytest.mark.asyncio async def test_failover_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4841,7 +4461,7 @@ def test_failover_instance_flattened_error(): @pytest.mark.asyncio async def test_failover_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4878,7 +4498,7 @@ async def test_failover_instance_flattened_async(): @pytest.mark.asyncio async def test_failover_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4924,25 +4544,6 @@ def test_delete_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.DeleteInstanceRequest() - - def test_delete_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5011,27 +4612,6 @@ def test_delete_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.DeleteInstanceRequest() - - @pytest.mark.asyncio async def test_delete_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5040,7 +4620,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5084,7 +4664,7 @@ async def test_delete_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.DeleteInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5147,7 +4727,7 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5217,7 +4797,7 @@ def test_delete_instance_flattened_error(): @pytest.mark.asyncio async def test_delete_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5246,7 +4826,7 @@ async def test_delete_instance_flattened_async(): @pytest.mark.asyncio async def test_delete_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5293,27 +4873,6 @@ def test_reschedule_maintenance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_reschedule_maintenance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.reschedule_maintenance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.RescheduleMaintenanceRequest() - - def test_reschedule_maintenance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5389,29 +4948,6 @@ def test_reschedule_maintenance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_reschedule_maintenance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.reschedule_maintenance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.RescheduleMaintenanceRequest() - - @pytest.mark.asyncio async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5420,7 +4956,7 @@ async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5465,7 +5001,7 @@ async def test_reschedule_maintenance_async( request_type=cloud_redis.RescheduleMaintenanceRequest, ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5532,7 +5068,7 @@ def test_reschedule_maintenance_field_headers(): @pytest.mark.asyncio async def test_reschedule_maintenance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5616,7 +5152,7 @@ def test_reschedule_maintenance_flattened_error(): @pytest.mark.asyncio async def test_reschedule_maintenance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5655,7 +5191,7 @@ async def test_reschedule_maintenance_flattened_async(): @pytest.mark.asyncio async def test_reschedule_maintenance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5669,60 +5205,18 @@ async def test_reschedule_maintenance_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_instances_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + 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 = cloud_redis.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_instances(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_instances_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.list_instances in client._transport._wrapped_methods @@ -5845,87 +5339,6 @@ def test_list_instances_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_list_instances" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_list_instances" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ListInstancesRequest.pb( - cloud_redis.ListInstancesRequest() - ) - 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 = cloud_redis.ListInstancesResponse.to_json( - cloud_redis.ListInstancesResponse() - ) - - request = cloud_redis.ListInstancesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.ListInstancesResponse() - - client.list_instances( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ListInstancesRequest -): - client = CloudRedisClient( - 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.list_instances(request) - - def test_list_instances_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6043,110 +5456,6 @@ def test_list_instances_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.GetInstanceRequest, - dict, - ], -) -def test_get_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( - name="name_value", - display_name="display_name_value", - location_id="location_id_value", - alternative_location_id="alternative_location_id_value", - redis_version="redis_version_value", - reserved_ip_range="reserved_ip_range_value", - secondary_ip_range="secondary_ip_range_value", - host="host_value", - port=453, - current_location_id="current_location_id_value", - state=cloud_redis.Instance.State.CREATING, - status_message="status_message_value", - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network="authorized_network_value", - persistence_iam_identity="persistence_iam_identity_value", - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint="read_endpoint_value", - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - customer_managed_key="customer_managed_key_value", - suspension_reasons=[ - cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE - ], - maintenance_version="maintenance_version_value", - available_maintenance_versions=["available_maintenance_versions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.location_id == "location_id_value" - assert response.alternative_location_id == "alternative_location_id_value" - assert response.redis_version == "redis_version_value" - assert response.reserved_ip_range == "reserved_ip_range_value" - assert response.secondary_ip_range == "secondary_ip_range_value" - assert response.host == "host_value" - assert response.port == 453 - assert response.current_location_id == "current_location_id_value" - assert response.state == cloud_redis.Instance.State.CREATING - assert response.status_message == "status_message_value" - assert response.tier == cloud_redis.Instance.Tier.BASIC - assert response.memory_size_gb == 1499 - assert response.authorized_network == "authorized_network_value" - assert response.persistence_iam_identity == "persistence_iam_identity_value" - assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING - assert response.auth_enabled is True - assert ( - response.transit_encryption_mode - == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION - ) - assert response.replica_count == 1384 - assert response.read_endpoint == "read_endpoint_value" - assert response.read_endpoint_port == 1920 - assert ( - response.read_replicas_mode - == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED - ) - assert response.customer_managed_key == "customer_managed_key_value" - assert response.suspension_reasons == [ - cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE - ] - assert response.maintenance_version == "maintenance_version_value" - assert response.available_maintenance_versions == [ - "available_maintenance_versions_value" - ] - - def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6264,93 +5573,16 @@ def test_get_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( +def test_get_instance_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), + transport="rest", ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_get_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) - 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 = cloud_redis.Instance.to_json(cloud_redis.Instance()) - request = cloud_redis.GetInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.Instance() - - client.get_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.GetInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance(request) - - -def test_get_instance_rest_flattened(): - client = CloudRedisClient( - 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 = cloud_redis.Instance() + # 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 = cloud_redis.Instance() # get arguments that satisfy an http rule for this method sample_request = { @@ -6399,52 +5631,6 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.GetInstanceAuthStringRequest, - dict, - ], -) -def test_get_instance_auth_string_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( - auth_string="auth_string_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.InstanceAuthString.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance_auth_string(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == "auth_string_value" - - def test_get_instance_auth_string_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6569,87 +5755,6 @@ def test_get_instance_auth_string_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_auth_string_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance_auth_string" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_get_instance_auth_string" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceAuthStringRequest.pb( - cloud_redis.GetInstanceAuthStringRequest() - ) - 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 = cloud_redis.InstanceAuthString.to_json( - cloud_redis.InstanceAuthString() - ) - - request = cloud_redis.GetInstanceAuthStringRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.InstanceAuthString() - - client.get_instance_auth_string( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_auth_string_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.GetInstanceAuthStringRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance_auth_string(request) - - def test_get_instance_auth_string_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6709,189 +5814,210 @@ def test_get_instance_auth_string_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_auth_string_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=cloud_redis.CreateInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id",)) + 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" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.CreateInstanceRequest, - dict, - ], -) -def test_create_instance_rest(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "labels": {}, - "location_id": "location_id_value", - "alternative_location_id": "alternative_location_id_value", - "redis_version": "redis_version_value", - "reserved_ip_range": "reserved_ip_range_value", - "secondary_ip_range": "secondary_ip_range_value", - "host": "host_value", - "port": 453, - "current_location_id": "current_location_id_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "status_message": "status_message_value", - "redis_configs": {}, - "tier": 1, - "memory_size_gb": 1499, - "authorized_network": "authorized_network_value", - "persistence_iam_identity": "persistence_iam_identity_value", - "connect_mode": 1, - "auth_enabled": True, - "server_ca_certs": [ - { - "serial_number": "serial_number_value", - "cert": "cert_value", - "create_time": {}, - "expire_time": {}, - "sha1_fingerprint": "sha1_fingerprint_value", + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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, } - ], - "transit_encryption_mode": 1, - "maintenance_policy": { - "create_time": {}, - "update_time": {}, - "description": "description_value", - "weekly_maintenance_window": [ - { - "day": 1, - "start_time": { - "hours": 561, - "minutes": 773, - "seconds": 751, - "nanos": 543, - }, - "duration": {"seconds": 751, "nanos": 543}, - } - ], - }, - "maintenance_schedule": { - "start_time": {}, - "end_time": {}, - "can_reschedule": True, - "schedule_deadline_time": {}, - }, - "replica_count": 1384, - "nodes": [{"id": "id_value", "zone": "zone_value"}], - "read_endpoint": "read_endpoint_value", - "read_endpoint_port": 1920, - "read_replicas_mode": 1, - "customer_managed_key": "customer_managed_key_value", - "persistence_config": { - "persistence_mode": 1, - "rdb_snapshot_period": 3, - "rdb_next_snapshot_time": {}, - "rdb_snapshot_start_time": {}, - }, - "suspension_reasons": [1], - "maintenance_version": "maintenance_version_value", - "available_maintenance_versions": [ - "available_maintenance_versions_value1", - "available_maintenance_versions_value2", - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response = client.create_instance(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_create_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("instanceId",)) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - request = request_type(**request_init) +def test_create_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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", + instance_id="instance_id_value", + instance=cloud_redis.Instance(name="name_value"), + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + client.create_instance(**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/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, + args[1], + ) -def test_create_instance_rest_use_cached_wrapped_rpc(): +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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_instance( + cloud_redis.CreateInstanceRequest(), + parent="parent_value", + instance_id="instance_id_value", + instance=cloud_redis.Instance(name="name_value"), + ) + + +def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6905,17 +6031,17 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.create_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6924,21 +6050,19 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=cloud_redis.CreateInstanceRequest, +def test_update_instance_rest_required_fields( + request_type=cloud_redis.UpdateInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6946,32 +6070,22 @@ def test_create_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("instance_id",)) + assert not set(unset_fields) - set(("update_mask",)) 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" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6992,7 +6106,7 @@ def test_create_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -7005,121 +6119,31 @@ def test_create_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.update_instance(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_instance_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) + unset_fields = transport.update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("instanceId",)) + set(("updateMask",)) & set( ( - "parent", - "instanceId", + "updateMask", "instance", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_create_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_create_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.CreateInstanceRequest.pb( - cloud_redis.CreateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.CreateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.CreateInstanceRequest -): - client = CloudRedisClient( - 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.create_instance(request) - - -def test_create_instance_rest_flattened(): +def test_update_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7131,12 +6155,13 @@ def test_create_instance_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - instance_id="instance_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), instance=cloud_redis.Instance(name="name_value"), ) mock_args.update(sample_request) @@ -7148,19 +6173,20 @@ def test_create_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_instance(**mock_args) + client.update_instance(**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/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, + "%s/v1/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, args[1], ) -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_update_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7169,199 +6195,208 @@ def test_create_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_instance( - cloud_redis.CreateInstanceRequest(), - parent="parent_value", - instance_id="instance_id_value", + client.update_instance( + cloud_redis.UpdateInstanceRequest(), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), instance=cloud_redis.Instance(name="name_value"), ) -def test_create_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_upgrade_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.upgrade_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.upgrade_instance + ] = mock_rpc + + request = {} + client.upgrade_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.upgrade_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_upgrade_instance_rest_required_fields( + request_type=cloud_redis.UpgradeInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + request_init = {} + request_init["name"] = "" + request_init["redis_version"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upgrade_instance._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["redisVersion"] = "redis_version_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upgrade_instance._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 "redisVersion" in jsonified_request + assert jsonified_request["redisVersion"] == "redis_version_value" -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.UpdateInstanceRequest, - dict, - ], -) -def test_update_instance_rest(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "display_name": "display_name_value", - "labels": {}, - "location_id": "location_id_value", - "alternative_location_id": "alternative_location_id_value", - "redis_version": "redis_version_value", - "reserved_ip_range": "reserved_ip_range_value", - "secondary_ip_range": "secondary_ip_range_value", - "host": "host_value", - "port": 453, - "current_location_id": "current_location_id_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "status_message": "status_message_value", - "redis_configs": {}, - "tier": 1, - "memory_size_gb": 1499, - "authorized_network": "authorized_network_value", - "persistence_iam_identity": "persistence_iam_identity_value", - "connect_mode": 1, - "auth_enabled": True, - "server_ca_certs": [ - { - "serial_number": "serial_number_value", - "cert": "cert_value", - "create_time": {}, - "expire_time": {}, - "sha1_fingerprint": "sha1_fingerprint_value", - } - ], - "transit_encryption_mode": 1, - "maintenance_policy": { - "create_time": {}, - "update_time": {}, - "description": "description_value", - "weekly_maintenance_window": [ - { - "day": 1, - "start_time": { - "hours": 561, - "minutes": 773, - "seconds": 751, - "nanos": 543, - }, - "duration": {"seconds": 751, "nanos": 543}, - } - ], - }, - "maintenance_schedule": { - "start_time": {}, - "end_time": {}, - "can_reschedule": True, - "schedule_deadline_time": {}, - }, - "replica_count": 1384, - "nodes": [{"id": "id_value", "zone": "zone_value"}], - "read_endpoint": "read_endpoint_value", - "read_endpoint_port": 1920, - "read_replicas_mode": 1, - "customer_managed_key": "customer_managed_key_value", - "persistence_config": { - "persistence_mode": 1, - "rdb_snapshot_period": 3, - "rdb_next_snapshot_time": {}, - "rdb_snapshot_start_time": {}, - }, - "suspension_reasons": [1], - "maintenance_version": "maintenance_version_value", - "available_maintenance_versions": [ - "available_maintenance_versions_value1", - "available_maintenance_versions_value2", - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis.UpdateInstanceRequest.meta.fields["instance"] + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response = client.upgrade_instance(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_upgrade_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + unset_fields = transport.upgrade_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "redisVersion", + ) + ) + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - request = request_type(**request_init) +def test_upgrade_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + redis_version="redis_version_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + client.upgrade_instance(**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/v1/{name=projects/*/locations/*/instances/*}:upgrade" + % client.transport._host, + args[1], + ) -def test_update_instance_rest_use_cached_wrapped_rpc(): +def test_upgrade_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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.upgrade_instance( + cloud_redis.UpgradeInstanceRequest(), + name="name_value", + redis_version="redis_version_value", + ) + + +def test_import_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7375,17 +6410,17 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert client._transport.import_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.import_instance] = mock_rpc request = {} - client.update_instance(request) + client.import_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7394,19 +6429,20 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_instance(request) + client.import_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_instance_rest_required_fields( - request_type=cloud_redis.UpdateInstanceRequest, +def test_import_instance_rest_required_fields( + request_type=cloud_redis.ImportInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7417,19 +6453,21 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).import_instance._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() - ).update_instance._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",)) + ).import_instance._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 = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7450,7 +6488,7 @@ def test_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -7463,119 +6501,34 @@ def test_update_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.import_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_instance_rest_unset_required_fields(): +def test_import_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) + unset_fields = transport.import_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) + set(()) & set( ( - "updateMask", - "instance", + "name", + "inputConfig", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( +def test_import_instance_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_update_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_update_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpdateInstanceRequest.pb( - cloud_redis.UpdateInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.UpdateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.UpdateInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/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.update_instance(request) - - -def test_update_instance_rest_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7585,13 +6538,15 @@ def test_update_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + "name": "projects/sample1/locations/sample2/instances/sample3" } # get truthy value for each flattened field mock_args = dict( - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - instance=cloud_redis.Instance(name="name_value"), + name="name_value", + input_config=cloud_redis.InputConfig( + gcs_source=cloud_redis.GcsSource(uri="uri_value") + ), ) mock_args.update(sample_request) @@ -7602,20 +6557,20 @@ def test_update_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_instance(**mock_args) + client.import_instance(**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/v1/{instance.name=projects/*/locations/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/instances/*}:import" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_import_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7624,55 +6579,16 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_instance( - cloud_redis.UpdateInstanceRequest(), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - instance=cloud_redis.Instance(name="name_value"), + client.import_instance( + cloud_redis.ImportInstanceRequest(), + name="name_value", + input_config=cloud_redis.InputConfig( + gcs_source=cloud_redis.GcsSource(uri="uri_value") + ), ) -def test_update_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.UpgradeInstanceRequest, - dict, - ], -) -def test_upgrade_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.upgrade_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_upgrade_instance_rest_use_cached_wrapped_rpc(): +def test_export_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7686,19 +6602,17 @@ def test_upgrade_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.upgrade_instance in client._transport._wrapped_methods + assert client._transport.export_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.upgrade_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.export_instance] = mock_rpc request = {} - client.upgrade_instance(request) + client.export_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7707,21 +6621,20 @@ def test_upgrade_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.upgrade_instance(request) + client.export_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_upgrade_instance_rest_required_fields( - request_type=cloud_redis.UpgradeInstanceRequest, +def test_export_instance_rest_required_fields( + request_type=cloud_redis.ExportInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} request_init["name"] = "" - request_init["redis_version"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7732,24 +6645,21 @@ def test_upgrade_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upgrade_instance._get_unset_required_fields(jsonified_request) + ).export_instance._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["redisVersion"] = "redis_version_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upgrade_instance._get_unset_required_fields(jsonified_request) + ).export_instance._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 "redisVersion" in jsonified_request - assert jsonified_request["redisVersion"] == "redis_version_value" client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7783,114 +6693,31 @@ def test_upgrade_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.upgrade_instance(request) + response = client.export_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_upgrade_instance_rest_unset_required_fields(): +def test_export_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.upgrade_instance._get_unset_required_fields({}) + unset_fields = transport.export_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "name", - "redisVersion", + "outputConfig", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_upgrade_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_upgrade_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_upgrade_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpgradeInstanceRequest.pb( - cloud_redis.UpgradeInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.UpgradeInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.upgrade_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_upgrade_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.UpgradeInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.upgrade_instance(request) - - -def test_upgrade_instance_rest_flattened(): +def test_export_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7909,7 +6736,9 @@ def test_upgrade_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", - redis_version="redis_version_value", + output_config=cloud_redis.OutputConfig( + gcs_destination=cloud_redis.GcsDestination(uri="uri_value") + ), ) mock_args.update(sample_request) @@ -7920,20 +6749,20 @@ def test_upgrade_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.upgrade_instance(**mock_args) + client.export_instance(**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/v1/{name=projects/*/locations/*/instances/*}:upgrade" + "%s/v1/{name=projects/*/locations/*/instances/*}:export" % client.transport._host, args[1], ) -def test_upgrade_instance_rest_flattened_error(transport: str = "rest"): +def test_export_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7942,79 +6771,42 @@ def test_upgrade_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.upgrade_instance( - cloud_redis.UpgradeInstanceRequest(), + client.export_instance( + cloud_redis.ExportInstanceRequest(), name="name_value", - redis_version="redis_version_value", + output_config=cloud_redis.OutputConfig( + gcs_destination=cloud_redis.GcsDestination(uri="uri_value") + ), ) -def test_upgrade_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.ImportInstanceRequest, - dict, - ], -) -def test_import_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_failover_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.import_instance in client._transport._wrapped_methods + assert client._transport.failover_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.import_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.failover_instance + ] = mock_rpc request = {} - client.import_instance(request) + client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8023,15 +6815,15 @@ def test_import_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.import_instance(request) + client.failover_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_import_instance_rest_required_fields( - request_type=cloud_redis.ImportInstanceRequest, +def test_failover_instance_rest_required_fields( + request_type=cloud_redis.FailoverInstanceRequest, ): transport_class = transports.CloudRedisRestTransport @@ -8047,7 +6839,7 @@ def test_import_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_instance._get_unset_required_fields(jsonified_request) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8056,7 +6848,7 @@ def test_import_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_instance._get_unset_required_fields(jsonified_request) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8095,114 +6887,23 @@ def test_import_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.import_instance(request) + response = client.failover_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_import_instance_rest_unset_required_fields(): +def test_failover_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.import_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "inputConfig", - ) - ) - ) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_import_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_import_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ImportInstanceRequest.pb( - cloud_redis.ImportInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.ImportInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ImportInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.import_instance(request) + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_import_instance_rest_flattened(): +def test_failover_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8221,9 +6922,7 @@ def test_import_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", - input_config=cloud_redis.InputConfig( - gcs_source=cloud_redis.GcsSource(uri="uri_value") - ), + data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, ) mock_args.update(sample_request) @@ -8234,20 +6933,20 @@ def test_import_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.import_instance(**mock_args) + client.failover_instance(**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/v1/{name=projects/*/locations/*/instances/*}:import" + "%s/v1/{name=projects/*/locations/*/instances/*}:failover" % client.transport._host, args[1], ) -def test_import_instance_rest_flattened_error(transport: str = "rest"): +def test_failover_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8256,57 +6955,14 @@ def test_import_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.import_instance( - cloud_redis.ImportInstanceRequest(), + client.failover_instance( + cloud_redis.FailoverInstanceRequest(), name="name_value", - input_config=cloud_redis.InputConfig( - gcs_source=cloud_redis.GcsSource(uri="uri_value") - ), + data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, ) -def test_import_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.ExportInstanceRequest, - dict, - ], -) -def test_export_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_instance_rest_use_cached_wrapped_rpc(): +def test_delete_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8320,17 +6976,17 @@ def test_export_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.export_instance in client._transport._wrapped_methods + assert client._transport.delete_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.export_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.export_instance(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8339,15 +6995,15 @@ def test_export_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.export_instance(request) + client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_export_instance_rest_required_fields( - request_type=cloud_redis.ExportInstanceRequest, +def test_delete_instance_rest_required_fields( + request_type=cloud_redis.DeleteInstanceRequest, ): transport_class = transports.CloudRedisRestTransport @@ -8363,7 +7019,7 @@ def test_export_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8372,7 +7028,7 @@ def test_export_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8398,10 +7054,9 @@ def test_export_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -8411,115 +7066,24 @@ def test_export_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.export_instance(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_export_instance_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.export_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "outputConfig", - ) - ) - ) + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_export_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_export_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ExportInstanceRequest.pb( - cloud_redis.ExportInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.ExportInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ExportInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.export_instance(request) - - -def test_export_instance_rest_flattened(): - client = CloudRedisClient( +def test_delete_instance_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -8537,9 +7101,6 @@ def test_export_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", - output_config=cloud_redis.OutputConfig( - gcs_destination=cloud_redis.GcsDestination(uri="uri_value") - ), ) mock_args.update(sample_request) @@ -8550,20 +7111,19 @@ def test_export_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.export_instance(**mock_args) + client.delete_instance(**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/v1/{name=projects/*/locations/*/instances/*}:export" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1], ) -def test_export_instance_rest_flattened_error(transport: str = "rest"): +def test_delete_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8572,57 +7132,13 @@ def test_export_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.export_instance( - cloud_redis.ExportInstanceRequest(), + client.delete_instance( + cloud_redis.DeleteInstanceRequest(), name="name_value", - output_config=cloud_redis.OutputConfig( - gcs_destination=cloud_redis.GcsDestination(uri="uri_value") - ), ) -def test_export_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.FailoverInstanceRequest, - dict, - ], -) -def test_failover_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.failover_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_failover_instance_rest_use_cached_wrapped_rpc(): +def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8636,7 +7152,10 @@ def test_failover_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.failover_instance in client._transport._wrapped_methods + assert ( + client._transport.reschedule_maintenance + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -8644,11 +7163,11 @@ def test_failover_instance_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.failover_instance + client._transport.reschedule_maintenance ] = mock_rpc request = {} - client.failover_instance(request) + client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8657,15 +7176,15 @@ def test_failover_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.failover_instance(request) + client.reschedule_maintenance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_failover_instance_rest_required_fields( - request_type=cloud_redis.FailoverInstanceRequest, +def test_reschedule_maintenance_rest_required_fields( + request_type=cloud_redis.RescheduleMaintenanceRequest, ): transport_class = transports.CloudRedisRestTransport @@ -8681,7 +7200,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8690,7 +7209,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -8729,106 +7248,31 @@ def test_failover_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.reschedule_maintenance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_failover_instance_rest_unset_required_fields(): +def test_reschedule_maintenance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.failover_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_failover_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_failover_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_failover_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.FailoverInstanceRequest.pb( - cloud_redis.FailoverInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = cloud_redis.FailoverInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.failover_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "rescheduleType", + ) ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_failover_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.FailoverInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.failover_instance(request) - -def test_failover_instance_rest_flattened(): +def test_reschedule_maintenance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8847,7 +7291,8 @@ def test_failover_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( name="name_value", - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) mock_args.update(sample_request) @@ -8858,20 +7303,20 @@ def test_failover_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.failover_instance(**mock_args) + client.reschedule_maintenance(**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/v1/{name=projects/*/locations/*/instances/*}:failover" + "%s/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" % client.transport._host, args[1], ) -def test_failover_instance_rest_flattened_error(transport: str = "rest"): +def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8880,1768 +7325,3574 @@ def test_failover_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.failover_instance( - cloud_redis.FailoverInstanceRequest(), + client.reschedule_maintenance( + cloud_redis.RescheduleMaintenanceRequest(), name="name_value", - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) -def test_failover_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), ) + with pytest.raises(ValueError): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.DeleteInstanceRequest, - dict, - ], -) -def test_delete_instance_rest(request_type): - client = CloudRedisClient( + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudRedisGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options=options, + transport=transport, + ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) - # 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 = operations_pb2.Operation(name="operations/spam") + # It is an error to provide scopes and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_instance(request) +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudRedisClient(transport=transport) + assert client.transport is transport - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel -def test_delete_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + transport = transports.CloudRedisGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisGrpcTransport, + transports.CloudRedisGrpcAsyncIOTransport, + transports.CloudRedisRestTransport, + ], +) +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() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc - request = {} - client.delete_instance(request) +def test_transport_kind_grpc(): + transport = CloudRedisClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() +def test_initialize_client_w_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None - client.delete_instance(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = cloud_redis.ListInstancesResponse() + client.list_instances(request=None) -def test_delete_instance_rest_required_fields( - request_type=cloud_redis.DeleteInstanceRequest, -): - transport_class = transports.CloudRedisRestTransport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() - 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, use_integers_for_enums=False) - ) + assert args[0] == request_msg - # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # verify required fields with default values are now present + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = cloud_redis.Instance() + client.get_instance(request=None) - jsonified_request["name"] = "name_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert args[0] == request_msg - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_auth_string_empty_call_grpc(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + call.return_value = cloud_redis.InstanceAuthString() + client.get_instance_auth_string(request=None) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + assert args[0] == request_msg - response = client.delete_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) -def test_delete_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upgrade_instance_empty_call_grpc(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), + transport="grpc", ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_delete_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_delete_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.DeleteInstanceRequest.pb( - cloud_redis.DeleteInstanceRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - request = cloud_redis.DeleteInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.upgrade_instance(request=None) - client.delete_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() - pre.assert_called_once() - post.assert_called_once() + assert args[0] == request_msg -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.DeleteInstanceRequest -): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_instance_empty_call_grpc(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_instance(request=None) - # 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.delete_instance(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() + assert args[0] == request_msg -def test_delete_instance_rest_flattened(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_instance_empty_call_grpc(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_instance(request=None) - client.delete_instance(**mock_args) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() - # 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/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, - args[1], - ) + assert args[0] == request_msg -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_instance_empty_call_grpc(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_instance( - cloud_redis.DeleteInstanceRequest(), - name="name_value", - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.failover_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() -def test_delete_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.RescheduleMaintenanceRequest, - dict, - ], -) -def test_reschedule_maintenance_rest(request_type): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.reschedule_maintenance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() - # Ensure method has been cached - assert ( - client._transport.reschedule_maintenance - in client._transport._wrapped_methods - ) + assert args[0] == request_msg - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.reschedule_maintenance - ] = mock_rpc - request = {} - client.reschedule_maintenance(request) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reschedule_maintenance(request=None) - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() - client.reschedule_maintenance(request) + assert args[0] == request_msg - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +def test_transport_kind_grpc_asyncio(): + transport = CloudRedisAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" -def test_reschedule_maintenance_rest_required_fields( - request_type=cloud_redis.RescheduleMaintenanceRequest, -): - transport_class = transports.CloudRedisRestTransport - 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, use_integers_for_enums=False) +def test_initialize_client_w_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) + assert client is not None - # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).reschedule_maintenance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # verify required fields with default values are now present + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) - jsonified_request["name"] = "name_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).reschedule_maintenance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + assert args[0] == request_msg - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.Instance( + name="name_value", + display_name="display_name_value", + location_id="location_id_value", + alternative_location_id="alternative_location_id_value", + redis_version="redis_version_value", + reserved_ip_range="reserved_ip_range_value", + secondary_ip_range="secondary_ip_range_value", + host="host_value", + port=453, + current_location_id="current_location_id_value", + state=cloud_redis.Instance.State.CREATING, + status_message="status_message_value", + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network="authorized_network_value", + persistence_iam_identity="persistence_iam_identity_value", + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint="read_endpoint_value", + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + customer_managed_key="customer_managed_key_value", + suspension_reasons=[ + cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE + ], + maintenance_version="maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + ) + ) + await client.get_instance(request=None) - response = client.reschedule_maintenance(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + assert args[0] == request_msg -def test_reschedule_maintenance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_auth_string_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "rescheduleType", + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.InstanceAuthString( + auth_string="auth_string_value", ) ) - ) + await client.get_instance_auth_string(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_reschedule_maintenance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_reschedule_maintenance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_reschedule_maintenance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.RescheduleMaintenanceRequest.pb( - cloud_redis.RescheduleMaintenanceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + assert args[0] == request_msg - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) - request = cloud_redis.RescheduleMaintenanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - client.reschedule_maintenance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.create_instance(request=None) - pre.assert_called_once() - post.assert_called_once() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() + assert args[0] == request_msg -def test_reschedule_maintenance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.RescheduleMaintenanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) - # 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.reschedule_maintenance(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() + assert args[0] == request_msg -def test_reschedule_maintenance_rest_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_upgrade_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.upgrade_instance(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.reschedule_maintenance(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # 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/v1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" - % client.transport._host, - args[1], + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.import_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() -def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.reschedule_maintenance( - cloud_redis.RescheduleMaintenanceRequest(), - name="name_value", - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.export_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() -def test_reschedule_maintenance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_failover_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - with pytest.raises(ValueError): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.failover_instance(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.delete_instance(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_reschedule_maintenance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.reschedule_maintenance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CloudRedisClient(transport=transport) - assert client.transport is transport + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_rest(): + transport = CloudRedisClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() ) - channel = transport.grpc_channel - assert channel + assert transport.kind == "rest" - transport = transports.CloudRedisGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_list_instances_rest_bad_request(request_type=cloud_redis.ListInstancesRequest): + client = CloudRedisClient( + 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) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisGrpcTransport, - transports.CloudRedisGrpcAsyncIOTransport, - transports.CloudRedisRestTransport, - ], -) -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() + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_instances(request) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "rest", + cloud_redis.ListInstancesRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = CloudRedisClient.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. +def test_list_instances_rest_call_success(request_type): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CloudRedisGrpcTransport, + 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) -def test_cloud_redis_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudRedisTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) - - -def test_cloud_redis_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CloudRedisTransport( - credentials=ga_credentials.AnonymousCredentials(), + # 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 = cloud_redis.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_instances", - "get_instance", - "get_instance_auth_string", - "create_instance", - "update_instance", - "upgrade_instance", - "import_instance", - "export_instance", - "failover_instance", - "delete_instance", - "reschedule_maintenance", - "get_location", - "list_locations", - "get_operation", - "cancel_operation", - "delete_operation", - "list_operations", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - with pytest.raises(NotImplementedError): - transport.close() + # Convert return value to protobuf type + return_value = cloud_redis.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_instances(request) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) -def test_cloud_redis_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.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudRedisRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ListInstancesRequest.pb( + cloud_redis.ListInstancesRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.ListInstancesResponse.to_json( + cloud_redis.ListInstancesResponse() + ) + req.return_value.content = return_value -def test_cloud_redis_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudRedisTransport() - adc.assert_called_once() + request = cloud_redis.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.ListInstancesResponse() + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=cloud_redis.GetInstanceRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( + name="name_value", + display_name="display_name_value", + location_id="location_id_value", + alternative_location_id="alternative_location_id_value", + redis_version="redis_version_value", + reserved_ip_range="reserved_ip_range_value", + secondary_ip_range="secondary_ip_range_value", + host="host_value", + port=453, + current_location_id="current_location_id_value", + state=cloud_redis.Instance.State.CREATING, + status_message="status_message_value", + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network="authorized_network_value", + persistence_iam_identity="persistence_iam_identity_value", + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint="read_endpoint_value", + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + customer_managed_key="customer_managed_key_value", + suspension_reasons=[ + cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE + ], + maintenance_version="maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.location_id == "location_id_value" + assert response.alternative_location_id == "alternative_location_id_value" + assert response.redis_version == "redis_version_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + assert response.secondary_ip_range == "secondary_ip_range_value" + assert response.host == "host_value" + assert response.port == 453 + assert response.current_location_id == "current_location_id_value" + assert response.state == cloud_redis.Instance.State.CREATING + assert response.status_message == "status_message_value" + assert response.tier == cloud_redis.Instance.Tier.BASIC + assert response.memory_size_gb == 1499 + assert response.authorized_network == "authorized_network_value" + assert response.persistence_iam_identity == "persistence_iam_identity_value" + assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING + assert response.auth_enabled is True + assert ( + response.transit_encryption_mode + == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION + ) + assert response.replica_count == 1384 + assert response.read_endpoint == "read_endpoint_value" + assert response.read_endpoint_port == 1920 + assert ( + response.read_replicas_mode + == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED + ) + assert response.customer_managed_key == "customer_managed_key_value" + assert response.suspension_reasons == [ + cloud_redis.Instance.SuspensionReason.CUSTOMER_MANAGED_KEY_ISSUE + ] + assert response.maintenance_version == "maintenance_version_value" + assert response.available_maintenance_versions == [ + "available_maintenance_versions_value" + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.Instance.to_json(cloud_redis.Instance()) + req.return_value.content = return_value + + request = cloud_redis.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.Instance() + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_auth_string_rest_bad_request( + request_type=cloud_redis.GetInstanceAuthStringRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance_auth_string(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.GetInstanceAuthStringRequest, + dict, + ], +) +def test_get_instance_auth_string_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( + auth_string="auth_string_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis.InstanceAuthString.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance_auth_string(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis.InstanceAuthString) + assert response.auth_string == "auth_string_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_auth_string_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance_auth_string" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_get_instance_auth_string" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.GetInstanceAuthStringRequest.pb( + cloud_redis.GetInstanceAuthStringRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.InstanceAuthString.to_json( + cloud_redis.InstanceAuthString() + ) + req.return_value.content = return_value + + request = cloud_redis.GetInstanceAuthStringRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.InstanceAuthString() + + client.get_instance_auth_string( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request( + request_type=cloud_redis.CreateInstanceRequest, +): + client = CloudRedisClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "labels": {}, + "location_id": "location_id_value", + "alternative_location_id": "alternative_location_id_value", + "redis_version": "redis_version_value", + "reserved_ip_range": "reserved_ip_range_value", + "secondary_ip_range": "secondary_ip_range_value", + "host": "host_value", + "port": 453, + "current_location_id": "current_location_id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "status_message": "status_message_value", + "redis_configs": {}, + "tier": 1, + "memory_size_gb": 1499, + "authorized_network": "authorized_network_value", + "persistence_iam_identity": "persistence_iam_identity_value", + "connect_mode": 1, + "auth_enabled": True, + "server_ca_certs": [ + { + "serial_number": "serial_number_value", + "cert": "cert_value", + "create_time": {}, + "expire_time": {}, + "sha1_fingerprint": "sha1_fingerprint_value", + } + ], + "transit_encryption_mode": 1, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "description": "description_value", + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + "duration": {"seconds": 751, "nanos": 543}, + } + ], + }, + "maintenance_schedule": { + "start_time": {}, + "end_time": {}, + "can_reschedule": True, + "schedule_deadline_time": {}, + }, + "replica_count": 1384, + "nodes": [{"id": "id_value", "zone": "zone_value"}], + "read_endpoint": "read_endpoint_value", + "read_endpoint_port": 1920, + "read_replicas_mode": 1, + "customer_managed_key": "customer_managed_key_value", + "persistence_config": { + "persistence_mode": 1, + "rdb_snapshot_period": 3, + "rdb_next_snapshot_time": {}, + "rdb_snapshot_start_time": {}, + }, + "suspension_reasons": [1], + "maintenance_version": "maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.CreateInstanceRequest.pb( + cloud_redis.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request( + request_type=cloud_redis.UpdateInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "display_name": "display_name_value", + "labels": {}, + "location_id": "location_id_value", + "alternative_location_id": "alternative_location_id_value", + "redis_version": "redis_version_value", + "reserved_ip_range": "reserved_ip_range_value", + "secondary_ip_range": "secondary_ip_range_value", + "host": "host_value", + "port": 453, + "current_location_id": "current_location_id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "status_message": "status_message_value", + "redis_configs": {}, + "tier": 1, + "memory_size_gb": 1499, + "authorized_network": "authorized_network_value", + "persistence_iam_identity": "persistence_iam_identity_value", + "connect_mode": 1, + "auth_enabled": True, + "server_ca_certs": [ + { + "serial_number": "serial_number_value", + "cert": "cert_value", + "create_time": {}, + "expire_time": {}, + "sha1_fingerprint": "sha1_fingerprint_value", + } + ], + "transit_encryption_mode": 1, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "description": "description_value", + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + "duration": {"seconds": 751, "nanos": 543}, + } + ], + }, + "maintenance_schedule": { + "start_time": {}, + "end_time": {}, + "can_reschedule": True, + "schedule_deadline_time": {}, + }, + "replica_count": 1384, + "nodes": [{"id": "id_value", "zone": "zone_value"}], + "read_endpoint": "read_endpoint_value", + "read_endpoint_port": 1920, + "read_replicas_mode": 1, + "customer_managed_key": "customer_managed_key_value", + "persistence_config": { + "persistence_mode": 1, + "rdb_snapshot_period": 3, + "rdb_next_snapshot_time": {}, + "rdb_snapshot_start_time": {}, + }, + "suspension_reasons": [1], + "maintenance_version": "maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.UpdateInstanceRequest.pb( + cloud_redis.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_upgrade_instance_rest_bad_request( + request_type=cloud_redis.UpgradeInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.upgrade_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.UpgradeInstanceRequest, + dict, + ], +) +def test_upgrade_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.upgrade_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upgrade_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_upgrade_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_upgrade_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.UpgradeInstanceRequest.pb( + cloud_redis.UpgradeInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.UpgradeInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.upgrade_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_instance_rest_bad_request( + request_type=cloud_redis.ImportInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.ImportInstanceRequest, + dict, + ], +) +def test_import_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_import_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_import_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ImportInstanceRequest.pb( + cloud_redis.ImportInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.ImportInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_instance_rest_bad_request( + request_type=cloud_redis.ExportInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.ExportInstanceRequest, + dict, + ], +) +def test_export_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_export_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_export_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ExportInstanceRequest.pb( + cloud_redis.ExportInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.ExportInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_failover_instance_rest_bad_request( + request_type=cloud_redis.FailoverInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.failover_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.FailoverInstanceRequest, + dict, + ], +) +def test_failover_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.failover_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_failover_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_failover_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_failover_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.FailoverInstanceRequest.pb( + cloud_redis.FailoverInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.FailoverInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.failover_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=cloud_redis.DeleteInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_delete_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.DeleteInstanceRequest.pb( + cloud_redis.DeleteInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_reschedule_maintenance_rest_bad_request( + request_type=cloud_redis.RescheduleMaintenanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.reschedule_maintenance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.RescheduleMaintenanceRequest, + dict, + ], +) +def test_reschedule_maintenance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.reschedule_maintenance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reschedule_maintenance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_reschedule_maintenance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_reschedule_maintenance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.RescheduleMaintenanceRequest.pb( + cloud_redis.RescheduleMaintenanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.RescheduleMaintenanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.reschedule_maintenance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) -def test_cloud_redis_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CloudRedisClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.CloudRedisGrpcTransport, - transports.CloudRedisGrpcAsyncIOTransport, + operations_pb2.DeleteOperationRequest, + dict, ], ) -def test_cloud_redis_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) +def test_delete_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.CloudRedisGrpcTransport, - transports.CloudRedisGrpcAsyncIOTransport, - transports.CloudRedisRestTransport, + operations_pb2.GetOperationRequest, + dict, ], ) -def test_cloud_redis_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_get_operation_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.CloudRedisGrpcTransport, grpc_helpers), - (transports.CloudRedisGrpcAsyncIOTransport, grpc_helpers_async), + operations_pb2.ListOperationsRequest, + dict, ], ) -def test_cloud_redis_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +def test_list_operations_rest(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - create_channel.assert_called_with( - "redis.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="redis.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") -@pytest.mark.parametrize( - "transport_class", - [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], -) -def test_cloud_redis_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() + req.return_value = response_value - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + response = client.list_operations(request) - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() -def test_cloud_redis_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.CloudRedisRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + assert args[0] == request_msg -def test_cloud_redis_rest_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_host_no_port(transport_name): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_auth_string_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com" + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + client.get_instance_auth_string(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) -def test_cloud_redis_host_with_port(transport_name): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="redis.googleapis.com:8000" - ), - transport=transport_name, - ) - assert client.transport._host == ( - "redis.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://redis.googleapis.com:8000" + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) -def test_cloud_redis_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CloudRedisClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CloudRedisClient( - credentials=creds2, - transport=transport_name, + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - session1 = client1.transport.list_instances._session - session2 = client2.transport.list_instances._session - assert session1 != session2 - session1 = client1.transport.get_instance._session - session2 = client2.transport.get_instance._session - assert session1 != session2 - session1 = client1.transport.get_instance_auth_string._session - session2 = client2.transport.get_instance_auth_string._session - assert session1 != session2 - session1 = client1.transport.create_instance._session - session2 = client2.transport.create_instance._session - assert session1 != session2 - session1 = client1.transport.update_instance._session - session2 = client2.transport.update_instance._session - assert session1 != session2 - session1 = client1.transport.upgrade_instance._session - session2 = client2.transport.upgrade_instance._session - assert session1 != session2 - session1 = client1.transport.import_instance._session - session2 = client2.transport.import_instance._session - assert session1 != session2 - session1 = client1.transport.export_instance._session - session2 = client2.transport.export_instance._session - assert session1 != session2 - session1 = client1.transport.failover_instance._session - session2 = client2.transport.failover_instance._session - assert session1 != session2 - session1 = client1.transport.delete_instance._session - session2 = client2.transport.delete_instance._session - assert session1 != session2 - session1 = client1.transport.reschedule_maintenance._session - session2 = client2.transport.reschedule_maintenance._session - assert session1 != session2 + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) -def test_cloud_redis_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() - # Check that channel is used if provided. - transport = transports.CloudRedisGrpcTransport( - host="squid.clam.whelk", - channel=channel, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upgrade_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + client.upgrade_instance(request=None) -def test_cloud_redis_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() - # Check that channel is used if provided. - transport = transports.CloudRedisGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + client.import_instance(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], -) -def test_cloud_redis_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + assert args[0] == request_msg - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + client.export_instance(request=None) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], -) -def test_cloud_redis_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + client.failover_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + assert args[0] == request_msg -def test_cloud_redis_grpc_lro_client(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + client.reschedule_maintenance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() -def test_cloud_redis_grpc_lro_async_client(): - client = CloudRedisAsyncClient( + assert args[0] == request_msg + + +def test_cloud_redis_rest_lro_client(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport="rest", ) transport = client.transport - # Ensure that we have a api-core operations client. + # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, - operations_v1.OperationsAsyncClient, + operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client -def test_instance_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}".format( - project=project, - location=location, - instance=instance, +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = CloudRedisClient.instance_path(project, location, instance) - assert expected == actual - - -def test_parse_instance_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = CloudRedisClient.instance_path(**expected) - - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_instance_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, + assert isinstance( + client.transport, + transports.CloudRedisGrpcTransport, ) - actual = CloudRedisClient.common_billing_account_path(billing_account) - assert expected == actual -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CloudRedisClient.common_billing_account_path(**expected) +def test_cloud_redis_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudRedisTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_common_billing_account_path(path) - assert expected == actual +def test_cloud_redis_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudRedisTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format( - folder=folder, + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_instances", + "get_instance", + "get_instance_auth_string", + "create_instance", + "update_instance", + "upgrade_instance", + "import_instance", + "export_instance", + "failover_instance", + "delete_instance", + "reschedule_maintenance", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", ) - actual = CloudRedisClient.common_folder_path(folder) - assert expected == actual + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + with pytest.raises(NotImplementedError): + transport.close() -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CloudRedisClient.common_folder_path(**expected) + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_common_folder_path(path) - assert expected == actual + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = CloudRedisClient.common_organization_path(organization) - assert expected == actual +def test_cloud_redis_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.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CloudRedisClient.common_organization_path(**expected) +def test_cloud_redis_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.redis_v1.services.cloud_redis.transports.CloudRedisTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudRedisTransport() + adc.assert_called_once() - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_common_organization_path(path) - assert expected == actual +def test_cloud_redis_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudRedisClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format( - project=project, - ) - actual = CloudRedisClient.common_project_path(project) - assert expected == actual +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisGrpcTransport, + transports.CloudRedisGrpcAsyncIOTransport, + ], +) +def test_cloud_redis_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CloudRedisClient.common_project_path(**expected) - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_common_project_path(path) - assert expected == actual +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisGrpcTransport, + transports.CloudRedisGrpcAsyncIOTransport, + transports.CloudRedisRestTransport, + ], +) +def test_cloud_redis_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = CloudRedisClient.common_location_path(project, location) - assert expected == actual +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudRedisGrpcTransport, grpc_helpers), + (transports.CloudRedisGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_redis_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + create_channel.assert_called_with( + "redis.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="redis.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CloudRedisClient.common_location_path(**expected) - # Check that the path construction is reversible. - actual = CloudRedisClient.parse_common_location_path(path) - assert expected == actual +@pytest.mark.parametrize( + "transport_class", + [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], +) +def test_cloud_redis_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) - with mock.patch.object( - transports.CloudRedisTransport, "_prep_wrapped_messages" - ) as prep: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.CloudRedisTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = CloudRedisClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, +def test_cloud_redis_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.CloudRedisRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) - prep.assert_called_once_with(client_info) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CloudRedisAsyncClient( +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_redis_host_no_port(transport_name): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "redis.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com" ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() -def test_get_location_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.GetLocationRequest -): +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_redis_host_with_port(transport_name): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + client_options=client_options.ClientOptions( + api_endpoint="redis.googleapis.com:8000" + ), + transport=transport_name, ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + assert client.transport._host == ( + "redis.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://redis.googleapis.com:8000" ) - # 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_location(request) - @pytest.mark.parametrize( - "request_type", + "transport_name", [ - locations_pb2.GetLocationRequest, - dict, + "rest", ], ) -def test_get_location_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_cloud_redis_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudRedisClient( + credentials=creds1, + transport=transport_name, ) - request_init = {"name": "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 = locations_pb2.Location() + client2 = CloudRedisClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.get_instance_auth_string._session + session2 = client2.transport.get_instance_auth_string._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.upgrade_instance._session + session2 = client2.transport.upgrade_instance._session + assert session1 != session2 + session1 = client1.transport.import_instance._session + session2 = client2.transport.import_instance._session + assert session1 != session2 + session1 = client1.transport.export_instance._session + session2 = client2.transport.export_instance._session + assert session1 != session2 + session1 = client1.transport.failover_instance._session + session2 = client2.transport.failover_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.reschedule_maintenance._session + session2 = client2.transport.reschedule_maintenance._session + assert session1 != session2 + + +def test_cloud_redis_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudRedisGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_cloud_redis_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) - response = client.get_location(request) + # Check that channel is used if provided. + transport = transports.CloudRedisGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], +) +def test_cloud_redis_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred -def test_list_locations_rest_bad_request( - transport: str = "rest", request_type=locations_pb2.ListLocationsRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel - request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() - # 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.list_locations(request) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( - "request_type", - [ - locations_pb2.ListLocationsRequest, - dict, - ], + "transport_class", + [transports.CloudRedisGrpcTransport, transports.CloudRedisGrpcAsyncIOTransport], ) -def test_list_locations_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1"} - 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 = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_cloud_redis_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() - response = client.list_locations(request) + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel -def test_cancel_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.CancelOperationRequest -): +def test_cloud_redis_grpc_lro_client(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) + transport = client.transport - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, ) - # 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.cancel_operation(request) + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): - client = CloudRedisClient( +def test_cloud_redis_grpc_lro_async_client(): + client = CloudRedisAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc_asyncio", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None + transport = client.transport - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client - response = client.cancel_operation(request) - # Establish that the response is the type that we expect. - assert response is None +def test_instance_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = CloudRedisClient.instance_path(project, location, instance) + assert expected == actual -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +def test_parse_instance_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = CloudRedisClient.instance_path(**expected) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_instance_path(path) + assert expected == actual - # 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.delete_operation(request) + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudRedisClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CloudRedisClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_operation(request) +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudRedisClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert response is None +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CloudRedisClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_common_folder_path(path) + assert expected == actual -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = CloudRedisClient.common_organization_path(organization) + assert expected == actual - # 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_operation(request) +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CloudRedisClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudRedisClient.common_project_path(project) + assert expected == actual - response = client.get_operation(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CloudRedisClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_common_project_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = CloudRedisClient.common_location_path(project, location) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CloudRedisClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = CloudRedisClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.list_operations(request) + with mock.patch.object( + transports.CloudRedisTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + with mock.patch.object( + transports.CloudRedisTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudRedisClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -10671,7 +10922,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10724,7 +10975,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10769,7 +11020,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -10810,7 +11061,7 @@ def test_cancel_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10863,7 +11114,7 @@ def test_cancel_operation_field_headers(): @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10908,7 +11159,7 @@ def test_cancel_operation_from_dict(): @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: @@ -10949,7 +11200,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11004,7 +11255,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11051,7 +11302,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -11094,7 +11345,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11149,7 +11400,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11196,7 +11447,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -11239,7 +11490,7 @@ def test_list_locations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11294,7 +11545,7 @@ def test_list_locations_field_headers(): @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11341,7 +11592,7 @@ def test_list_locations_from_dict(): @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -11384,7 +11635,7 @@ def test_get_location(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11436,7 +11687,7 @@ def test_get_location_field_headers(): @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = CloudRedisAsyncClient(credentials=ga_credentials.AnonymousCredentials()) + client = CloudRedisAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -11482,7 +11733,7 @@ def test_get_location_from_dict(): @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_locations), "__call__") as call: @@ -11498,22 +11749,41 @@ async def test_get_location_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-redis/tests/unit/gapic/redis_v1beta1/test_cloud_redis.py b/packages/google-cloud-redis/tests/unit/gapic/redis_v1beta1/test_cloud_redis.py index 649cddc3eb36..cbfb4b09d57c 100644 --- a/packages/google-cloud-redis/tests/unit/gapic/redis_v1beta1/test_cloud_redis.py +++ b/packages/google-cloud-redis/tests/unit/gapic/redis_v1beta1/test_cloud_redis.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,17 +65,9 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_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.type import dayofweek_pb2 # type: ignore from google.type import timeofday_pb2 # type: ignore -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.redis_v1beta1.services.cloud_redis import ( CloudRedisAsyncClient, @@ -69,10 +78,24 @@ from google.cloud.redis_v1beta1.types import cloud_redis +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1131,25 +1154,6 @@ def test_list_instances(request_type, transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] -def test_list_instances_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ListInstancesRequest() - - def test_list_instances_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1215,30 +1219,6 @@ def test_list_instances_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_instances_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = await client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ListInstancesRequest() - - @pytest.mark.asyncio async def test_list_instances_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1247,7 +1227,7 @@ async def test_list_instances_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1286,7 +1266,7 @@ async def test_list_instances_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ListInstancesRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1354,7 +1334,7 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1424,7 +1404,7 @@ def test_list_instances_flattened_error(): @pytest.mark.asyncio async def test_list_instances_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1453,7 +1433,7 @@ async def test_list_instances_flattened_async(): @pytest.mark.asyncio async def test_list_instances_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1563,7 +1543,7 @@ def test_list_instances_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_instances_async_pager(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1613,7 +1593,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1745,25 +1725,6 @@ def test_get_instance(request_type, transport: str = "grpc"): ) -def test_get_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceRequest() - - def test_get_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1827,51 +1788,6 @@ def test_get_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.Instance( - name="name_value", - display_name="display_name_value", - location_id="location_id_value", - alternative_location_id="alternative_location_id_value", - redis_version="redis_version_value", - reserved_ip_range="reserved_ip_range_value", - secondary_ip_range="secondary_ip_range_value", - host="host_value", - port=453, - current_location_id="current_location_id_value", - state=cloud_redis.Instance.State.CREATING, - status_message="status_message_value", - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network="authorized_network_value", - persistence_iam_identity="persistence_iam_identity_value", - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint="read_endpoint_value", - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - ) - ) - response = await client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceRequest() - - @pytest.mark.asyncio async def test_get_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1880,7 +1796,7 @@ async def test_get_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1919,7 +1835,7 @@ async def test_get_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.GetInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2035,7 +1951,7 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2105,7 +2021,7 @@ def test_get_instance_flattened_error(): @pytest.mark.asyncio async def test_get_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2134,7 +2050,7 @@ async def test_get_instance_flattened_async(): @pytest.mark.asyncio async def test_get_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2184,27 +2100,6 @@ def test_get_instance_auth_string(request_type, transport: str = "grpc"): assert response.auth_string == "auth_string_value" -def test_get_instance_auth_string_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_instance_auth_string() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceAuthStringRequest() - - def test_get_instance_auth_string_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2275,31 +2170,6 @@ def test_get_instance_auth_string_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_instance_auth_string_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance_auth_string), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - cloud_redis.InstanceAuthString( - auth_string="auth_string_value", - ) - ) - response = await client.get_instance_auth_string() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.GetInstanceAuthStringRequest() - - @pytest.mark.asyncio async def test_get_instance_auth_string_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2308,7 +2178,7 @@ async def test_get_instance_auth_string_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2348,7 +2218,7 @@ async def test_get_instance_auth_string_async( request_type=cloud_redis.GetInstanceAuthStringRequest, ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2418,7 +2288,7 @@ def test_get_instance_auth_string_field_headers(): @pytest.mark.asyncio async def test_get_instance_auth_string_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2492,7 +2362,7 @@ def test_get_instance_auth_string_flattened_error(): @pytest.mark.asyncio async def test_get_instance_auth_string_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2523,7 +2393,7 @@ async def test_get_instance_auth_string_flattened_async(): @pytest.mark.asyncio async def test_get_instance_auth_string_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2568,25 +2438,6 @@ def test_create_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.CreateInstanceRequest() - - def test_create_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2657,27 +2508,6 @@ def test_create_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.CreateInstanceRequest() - - @pytest.mark.asyncio async def test_create_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2686,7 +2516,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2730,7 +2560,7 @@ async def test_create_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.CreateInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2793,7 +2623,7 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio async def test_create_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2873,7 +2703,7 @@ def test_create_instance_flattened_error(): @pytest.mark.asyncio async def test_create_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2910,7 +2740,7 @@ async def test_create_instance_flattened_async(): @pytest.mark.asyncio async def test_create_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2957,25 +2787,6 @@ def test_update_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpdateInstanceRequest() - - def test_update_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3040,27 +2851,6 @@ def test_update_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpdateInstanceRequest() - - @pytest.mark.asyncio async def test_update_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3069,7 +2859,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3113,7 +2903,7 @@ async def test_update_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.UpdateInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3176,7 +2966,7 @@ def test_update_instance_field_headers(): @pytest.mark.asyncio async def test_update_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3251,7 +3041,7 @@ def test_update_instance_flattened_error(): @pytest.mark.asyncio async def test_update_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3284,7 +3074,7 @@ async def test_update_instance_flattened_async(): @pytest.mark.asyncio async def test_update_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3330,25 +3120,6 @@ def test_upgrade_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_upgrade_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.upgrade_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpgradeInstanceRequest() - - def test_upgrade_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3421,27 +3192,6 @@ def test_upgrade_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_upgrade_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.upgrade_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.UpgradeInstanceRequest() - - @pytest.mark.asyncio async def test_upgrade_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3450,7 +3200,7 @@ async def test_upgrade_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3494,7 +3244,7 @@ async def test_upgrade_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.UpgradeInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3557,7 +3307,7 @@ def test_upgrade_instance_field_headers(): @pytest.mark.asyncio async def test_upgrade_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3632,7 +3382,7 @@ def test_upgrade_instance_flattened_error(): @pytest.mark.asyncio async def test_upgrade_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3665,7 +3415,7 @@ async def test_upgrade_instance_flattened_async(): @pytest.mark.asyncio async def test_upgrade_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3711,25 +3461,6 @@ def test_import_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ImportInstanceRequest() - - def test_import_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3798,27 +3529,6 @@ def test_import_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ImportInstanceRequest() - - @pytest.mark.asyncio async def test_import_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3827,7 +3537,7 @@ async def test_import_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3871,7 +3581,7 @@ async def test_import_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ImportInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3934,7 +3644,7 @@ def test_import_instance_field_headers(): @pytest.mark.asyncio async def test_import_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4015,7 +3725,7 @@ def test_import_instance_flattened_error(): @pytest.mark.asyncio async def test_import_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4052,7 +3762,7 @@ async def test_import_instance_flattened_async(): @pytest.mark.asyncio async def test_import_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4100,25 +3810,6 @@ def test_export_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ExportInstanceRequest() - - def test_export_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4187,27 +3878,6 @@ def test_export_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.ExportInstanceRequest() - - @pytest.mark.asyncio async def test_export_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4216,7 +3886,7 @@ async def test_export_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4260,7 +3930,7 @@ async def test_export_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.ExportInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4323,7 +3993,7 @@ def test_export_instance_field_headers(): @pytest.mark.asyncio async def test_export_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4404,7 +4074,7 @@ def test_export_instance_flattened_error(): @pytest.mark.asyncio async def test_export_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4441,7 +4111,7 @@ async def test_export_instance_flattened_async(): @pytest.mark.asyncio async def test_export_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4491,27 +4161,6 @@ def test_failover_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_failover_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.failover_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.FailoverInstanceRequest() - - def test_failover_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4584,29 +4233,6 @@ def test_failover_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_failover_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.failover_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.FailoverInstanceRequest() - - @pytest.mark.asyncio async def test_failover_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4615,7 +4241,7 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4659,7 +4285,7 @@ async def test_failover_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.FailoverInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4726,7 +4352,7 @@ def test_failover_instance_field_headers(): @pytest.mark.asyncio async def test_failover_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4807,7 +4433,7 @@ def test_failover_instance_flattened_error(): @pytest.mark.asyncio async def test_failover_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4844,7 +4470,7 @@ async def test_failover_instance_flattened_async(): @pytest.mark.asyncio async def test_failover_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4890,25 +4516,6 @@ def test_delete_instance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.DeleteInstanceRequest() - - def test_delete_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4977,27 +4584,6 @@ def test_delete_instance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_instance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.DeleteInstanceRequest() - - @pytest.mark.asyncio async def test_delete_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5006,7 +4592,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5050,7 +4636,7 @@ async def test_delete_instance_async( transport: str = "grpc_asyncio", request_type=cloud_redis.DeleteInstanceRequest ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5113,7 +4699,7 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5183,7 +4769,7 @@ def test_delete_instance_flattened_error(): @pytest.mark.asyncio async def test_delete_instance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5212,7 +4798,7 @@ async def test_delete_instance_flattened_async(): @pytest.mark.asyncio async def test_delete_instance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5259,27 +4845,6 @@ def test_reschedule_maintenance(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_reschedule_maintenance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.reschedule_maintenance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.RescheduleMaintenanceRequest() - - def test_reschedule_maintenance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5355,29 +4920,6 @@ def test_reschedule_maintenance_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_reschedule_maintenance_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.reschedule_maintenance), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.reschedule_maintenance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == cloud_redis.RescheduleMaintenanceRequest() - - @pytest.mark.asyncio async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5386,7 +4928,7 @@ async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5431,7 +4973,7 @@ async def test_reschedule_maintenance_async( request_type=cloud_redis.RescheduleMaintenanceRequest, ): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5498,7 +5040,7 @@ def test_reschedule_maintenance_field_headers(): @pytest.mark.asyncio async def test_reschedule_maintenance_field_headers_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5582,7 +5124,7 @@ def test_reschedule_maintenance_flattened_error(): @pytest.mark.asyncio async def test_reschedule_maintenance_flattened_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5621,7 +5163,7 @@ async def test_reschedule_maintenance_flattened_async(): @pytest.mark.asyncio async def test_reschedule_maintenance_flattened_error_async(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5635,48 +5177,6 @@ async def test_reschedule_maintenance_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.ListInstancesRequest, - dict, - ], -) -def test_list_instances_rest(request_type): - client = CloudRedisClient( - 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 = cloud_redis.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_instances(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - def test_list_instances_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5811,91 +5311,10 @@ def test_list_instances_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( +def test_list_instances_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_list_instances" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_list_instances" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.ListInstancesRequest.pb( - cloud_redis.ListInstancesRequest() - ) - 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 = cloud_redis.ListInstancesResponse.to_json( - cloud_redis.ListInstancesResponse() - ) - - request = cloud_redis.ListInstancesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.ListInstancesResponse() - - client.list_instances( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ListInstancesRequest -): - client = CloudRedisClient( - 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.list_instances(request) - - -def test_list_instances_rest_flattened(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -6010,96 +5429,6 @@ def test_list_instances_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.GetInstanceRequest, - dict, - ], -) -def test_get_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( - name="name_value", - display_name="display_name_value", - location_id="location_id_value", - alternative_location_id="alternative_location_id_value", - redis_version="redis_version_value", - reserved_ip_range="reserved_ip_range_value", - secondary_ip_range="secondary_ip_range_value", - host="host_value", - port=453, - current_location_id="current_location_id_value", - state=cloud_redis.Instance.State.CREATING, - status_message="status_message_value", - tier=cloud_redis.Instance.Tier.BASIC, - memory_size_gb=1499, - authorized_network="authorized_network_value", - persistence_iam_identity="persistence_iam_identity_value", - connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, - auth_enabled=True, - transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, - replica_count=1384, - read_endpoint="read_endpoint_value", - read_endpoint_port=1920, - read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.location_id == "location_id_value" - assert response.alternative_location_id == "alternative_location_id_value" - assert response.redis_version == "redis_version_value" - assert response.reserved_ip_range == "reserved_ip_range_value" - assert response.secondary_ip_range == "secondary_ip_range_value" - assert response.host == "host_value" - assert response.port == 453 - assert response.current_location_id == "current_location_id_value" - assert response.state == cloud_redis.Instance.State.CREATING - assert response.status_message == "status_message_value" - assert response.tier == cloud_redis.Instance.Tier.BASIC - assert response.memory_size_gb == 1499 - assert response.authorized_network == "authorized_network_value" - assert response.persistence_iam_identity == "persistence_iam_identity_value" - assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING - assert response.auth_enabled is True - assert ( - response.transit_encryption_mode - == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION - ) - assert response.replica_count == 1384 - assert response.read_endpoint == "read_endpoint_value" - assert response.read_endpoint_port == 1920 - assert ( - response.read_replicas_mode - == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED - ) - - def test_get_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6217,83 +5546,6 @@ def test_get_instance_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_get_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) - 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 = cloud_redis.Instance.to_json(cloud_redis.Instance()) - - request = cloud_redis.GetInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.Instance() - - client.get_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.GetInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance(request) - - def test_get_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6353,70 +5605,24 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_get_instance_auth_string_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.GetInstanceAuthStringRequest, - dict, - ], -) -def test_get_instance_auth_string_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( - auth_string="auth_string_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cloud_redis.InstanceAuthString.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_instance_auth_string(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, cloud_redis.InstanceAuthString) - assert response.auth_string == "auth_string_value" - - -def test_get_instance_auth_string_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.get_instance_auth_string - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.get_instance_auth_string + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -6523,87 +5729,6 @@ def test_get_instance_auth_string_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_auth_string_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), - ) - client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance_auth_string" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_get_instance_auth_string" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.GetInstanceAuthStringRequest.pb( - cloud_redis.GetInstanceAuthStringRequest() - ) - 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 = cloud_redis.InstanceAuthString.to_json( - cloud_redis.InstanceAuthString() - ) - - request = cloud_redis.GetInstanceAuthStringRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = cloud_redis.InstanceAuthString() - - client.get_instance_auth_string( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_auth_string_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.GetInstanceAuthStringRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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.get_instance_auth_string(request) - - def test_get_instance_auth_string_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6663,182 +5788,211 @@ def test_get_instance_auth_string_rest_flattened_error(transport: str = "rest"): ) -def test_get_instance_auth_string_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_create_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=cloud_redis.CreateInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id",)) + 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" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.CreateInstanceRequest, - dict, - ], -) -def test_create_instance_rest(request_type): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "labels": {}, - "location_id": "location_id_value", - "alternative_location_id": "alternative_location_id_value", - "redis_version": "redis_version_value", - "reserved_ip_range": "reserved_ip_range_value", - "secondary_ip_range": "secondary_ip_range_value", - "host": "host_value", - "port": 453, - "current_location_id": "current_location_id_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "status_message": "status_message_value", - "redis_configs": {}, - "tier": 1, - "memory_size_gb": 1499, - "authorized_network": "authorized_network_value", - "persistence_iam_identity": "persistence_iam_identity_value", - "connect_mode": 1, - "auth_enabled": True, - "server_ca_certs": [ - { - "serial_number": "serial_number_value", - "cert": "cert_value", - "create_time": {}, - "expire_time": {}, - "sha1_fingerprint": "sha1_fingerprint_value", + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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, } - ], - "transit_encryption_mode": 1, - "maintenance_policy": { - "create_time": {}, - "update_time": {}, - "description": "description_value", - "weekly_maintenance_window": [ - { - "day": 1, - "start_time": { - "hours": 561, - "minutes": 773, - "seconds": 751, - "nanos": 543, - }, - "duration": {"seconds": 751, "nanos": 543}, - } - ], - }, - "maintenance_schedule": { - "start_time": {}, - "end_time": {}, - "can_reschedule": True, - "schedule_deadline_time": {}, - }, - "replica_count": 1384, - "nodes": [{"id": "id_value", "zone": "zone_value"}], - "read_endpoint": "read_endpoint_value", - "read_endpoint_port": 1920, - "read_replicas_mode": 1, - "persistence_config": { - "persistence_mode": 1, - "rdb_snapshot_period": 3, - "rdb_next_snapshot_time": {}, - "rdb_snapshot_start_time": {}, - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response = client.create_instance(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_create_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("instanceId",)) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - request = request_type(**request_init) +def test_create_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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", + instance_id="instance_id_value", + instance=cloud_redis.Instance(name="name_value"), + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + client.create_instance(**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/v1beta1/{parent=projects/*/locations/*}/instances" + % client.transport._host, + args[1], + ) -def test_create_instance_rest_use_cached_wrapped_rpc(): +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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_instance( + cloud_redis.CreateInstanceRequest(), + parent="parent_value", + instance_id="instance_id_value", + instance=cloud_redis.Instance(name="name_value"), + ) + + +def test_update_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6852,17 +6006,17 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.create_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6871,21 +6025,19 @@ def test_create_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_instance_rest_required_fields( - request_type=cloud_redis.CreateInstanceRequest, +def test_update_instance_rest_required_fields( + request_type=cloud_redis.UpdateInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6893,32 +6045,22 @@ def test_create_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("instance_id",)) + assert not set(unset_fields) - set(("update_mask",)) 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" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6939,7 +6081,7 @@ def test_create_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6952,121 +6094,225 @@ def test_create_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.update_instance(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_instance_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) + unset_fields = transport.update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("instanceId",)) + set(("updateMask",)) & set( ( - "parent", - "instanceId", + "updateMask", "instance", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( +def test_update_instance_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), + transport="rest", ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_create_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_create_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.CreateInstanceRequest.pb( - cloud_redis.CreateInstanceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + instance=cloud_redis.Instance(name="name_value"), ) + mock_args.update(sample_request) - request = cloud_redis.CreateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.create_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.update_instance(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v1beta1/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.CreateInstanceRequest -): +def test_update_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_instance( + cloud_redis.UpdateInstanceRequest(), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + instance=cloud_redis.Instance(name="name_value"), + ) + + +def test_upgrade_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.upgrade_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.upgrade_instance + ] = mock_rpc + + request = {} + client.upgrade_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.upgrade_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_upgrade_instance_rest_required_fields( + request_type=cloud_redis.UpgradeInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + request_init = {} + request_init["name"] = "" + request_init["redis_version"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # 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_instance(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upgrade_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_create_instance_rest_flattened(): + jsonified_request["name"] = "name_value" + jsonified_request["redisVersion"] = "redis_version_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upgrade_instance._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 "redisVersion" in jsonified_request + assert jsonified_request["redisVersion"] == "redis_version_value" + + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.upgrade_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_upgrade_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.upgrade_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "redisVersion", + ) + ) + ) + + +def test_upgrade_instance_rest_flattened(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7078,13 +6324,14 @@ def test_create_instance_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - instance_id="instance_id_value", - instance=cloud_redis.Instance(name="name_value"), + name="name_value", + redis_version="redis_version_value", ) mock_args.update(sample_request) @@ -7095,20 +6342,20 @@ def test_create_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_instance(**mock_args) + client.upgrade_instance(**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/v1beta1/{parent=projects/*/locations/*}/instances" + "%s/v1beta1/{name=projects/*/locations/*/instances/*}:upgrade" % client.transport._host, args[1], ) -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_upgrade_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7117,216 +6364,38 @@ def test_create_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_instance( - cloud_redis.CreateInstanceRequest(), - parent="parent_value", - instance_id="instance_id_value", - instance=cloud_redis.Instance(name="name_value"), + client.upgrade_instance( + cloud_redis.UpgradeInstanceRequest(), + name="name_value", + redis_version="redis_version_value", ) -def test_create_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_import_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.UpdateInstanceRequest, - dict, - ], -) -def test_update_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "display_name": "display_name_value", - "labels": {}, - "location_id": "location_id_value", - "alternative_location_id": "alternative_location_id_value", - "redis_version": "redis_version_value", - "reserved_ip_range": "reserved_ip_range_value", - "secondary_ip_range": "secondary_ip_range_value", - "host": "host_value", - "port": 453, - "current_location_id": "current_location_id_value", - "create_time": {"seconds": 751, "nanos": 543}, - "state": 1, - "status_message": "status_message_value", - "redis_configs": {}, - "tier": 1, - "memory_size_gb": 1499, - "authorized_network": "authorized_network_value", - "persistence_iam_identity": "persistence_iam_identity_value", - "connect_mode": 1, - "auth_enabled": True, - "server_ca_certs": [ - { - "serial_number": "serial_number_value", - "cert": "cert_value", - "create_time": {}, - "expire_time": {}, - "sha1_fingerprint": "sha1_fingerprint_value", - } - ], - "transit_encryption_mode": 1, - "maintenance_policy": { - "create_time": {}, - "update_time": {}, - "description": "description_value", - "weekly_maintenance_window": [ - { - "day": 1, - "start_time": { - "hours": 561, - "minutes": 773, - "seconds": 751, - "nanos": 543, - }, - "duration": {"seconds": 751, "nanos": 543}, - } - ], - }, - "maintenance_schedule": { - "start_time": {}, - "end_time": {}, - "can_reschedule": True, - "schedule_deadline_time": {}, - }, - "replica_count": 1384, - "nodes": [{"id": "id_value", "zone": "zone_value"}], - "read_endpoint": "read_endpoint_value", - "read_endpoint_port": 1920, - "read_replicas_mode": 1, - "persistence_config": { - "persistence_mode": 1, - "rdb_snapshot_period": 3, - "rdb_next_snapshot_time": {}, - "rdb_snapshot_start_time": {}, - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = cloud_redis.UpdateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert client._transport.import_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.import_instance] = mock_rpc request = {} - client.update_instance(request) + client.import_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7335,19 +6404,20 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_instance(request) + client.import_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_instance_rest_required_fields( - request_type=cloud_redis.UpdateInstanceRequest, +def test_import_instance_rest_required_fields( + request_type=cloud_redis.ImportInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7358,19 +6428,21 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).import_instance._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() - ).update_instance._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",)) + ).import_instance._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 = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7391,7 +6463,7 @@ def test_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -7404,137 +6476,54 @@ def test_update_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.import_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_instance_rest_unset_required_fields(): +def test_import_instance_rest_unset_required_fields(): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) + unset_fields = transport.import_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) + set(()) & set( ( - "updateMask", - "instance", + "name", + "inputConfig", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): - transport = transports.CloudRedisRestTransport( +def test_import_instance_rest_flattened(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CloudRedisRestInterceptor(), + transport="rest", ) - client = CloudRedisClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_update_instance" - ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_update_instance" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = cloud_redis.UpdateInstanceRequest.pb( - cloud_redis.UpdateInstanceRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + input_config=cloud_redis.InputConfig( + gcs_source=cloud_redis.GcsSource(uri="uri_value") + ), ) - - request = cloud_redis.UpdateInstanceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_instance( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.UpdateInstanceRequest -): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/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.update_instance(request) - - -def test_update_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - instance=cloud_redis.Instance(name="name_value"), - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7543,20 +6532,20 @@ def test_update_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_instance(**mock_args) + client.import_instance(**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/v1beta1/{instance.name=projects/*/locations/*/instances/*}" + "%s/v1beta1/{name=projects/*/locations/*/instances/*}:import" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_import_instance_rest_flattened_error(transport: str = "rest"): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7565,55 +6554,16 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_instance( - cloud_redis.UpdateInstanceRequest(), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - instance=cloud_redis.Instance(name="name_value"), + client.import_instance( + cloud_redis.ImportInstanceRequest(), + name="name_value", + input_config=cloud_redis.InputConfig( + gcs_source=cloud_redis.GcsSource(uri="uri_value") + ), ) -def test_update_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - cloud_redis.UpgradeInstanceRequest, - dict, - ], -) -def test_upgrade_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.upgrade_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_upgrade_instance_rest_use_cached_wrapped_rpc(): +def test_export_instance_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7627,19 +6577,17 @@ def test_upgrade_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.upgrade_instance in client._transport._wrapped_methods + assert client._transport.export_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.upgrade_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.export_instance] = mock_rpc request = {} - client.upgrade_instance(request) + client.export_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7648,21 +6596,20 @@ def test_upgrade_instance_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.upgrade_instance(request) + client.export_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_upgrade_instance_rest_required_fields( - request_type=cloud_redis.UpgradeInstanceRequest, +def test_export_instance_rest_required_fields( + request_type=cloud_redis.ExportInstanceRequest, ): transport_class = transports.CloudRedisRestTransport request_init = {} request_init["name"] = "" - request_init["redis_version"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7673,24 +6620,21 @@ def test_upgrade_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upgrade_instance._get_unset_required_fields(jsonified_request) + ).export_instance._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["redisVersion"] = "redis_version_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).upgrade_instance._get_unset_required_fields(jsonified_request) + ).export_instance._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 "redisVersion" in jsonified_request - assert jsonified_request["redisVersion"] == "redis_version_value" client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7724,32 +6668,2174 @@ def test_upgrade_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.upgrade_instance(request) + response = client.export_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_upgrade_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) +def test_export_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "outputConfig", + ) + ) + ) + + +def test_export_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + output_config=cloud_redis.OutputConfig( + gcs_destination=cloud_redis.GcsDestination(uri="uri_value") + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.export_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:export" + % client.transport._host, + args[1], + ) + + +def test_export_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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.export_instance( + cloud_redis.ExportInstanceRequest(), + name="name_value", + output_config=cloud_redis.OutputConfig( + gcs_destination=cloud_redis.GcsDestination(uri="uri_value") + ), + ) + + +def test_failover_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.failover_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.failover_instance + ] = mock_rpc + + request = {} + client.failover_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.failover_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_failover_instance_rest_required_fields( + request_type=cloud_redis.FailoverInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).failover_instance._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() + ).failover_instance._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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.failover_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_failover_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_failover_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.failover_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:failover" + % client.transport._host, + args[1], + ) + + +def test_failover_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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.failover_instance( + cloud_redis.FailoverInstanceRequest(), + name="name_value", + data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, + ) + + +def test_delete_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + + request = {} + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_instance_rest_required_fields( + request_type=cloud_redis.DeleteInstanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_instance._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() + ).delete_instance._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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_instance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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.delete_instance( + cloud_redis.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.reschedule_maintenance + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.reschedule_maintenance + ] = mock_rpc + + request = {} + client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reschedule_maintenance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_reschedule_maintenance_rest_required_fields( + request_type=cloud_redis.RescheduleMaintenanceRequest, +): + transport_class = transports.CloudRedisRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reschedule_maintenance._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() + ).reschedule_maintenance._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 = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.reschedule_maintenance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reschedule_maintenance_rest_unset_required_fields(): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "rescheduleType", + ) + ) + ) + + +def test_reschedule_maintenance_rest_flattened(): + client = CloudRedisClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.reschedule_maintenance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" + % client.transport._host, + args[1], + ) + + +def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): + client = CloudRedisClient( + 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.reschedule_maintenance( + cloud_redis.RescheduleMaintenanceRequest(), + name="name_value", + reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudRedisClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudRedisClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudRedisGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudRedisGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudRedisGrpcTransport, + transports.CloudRedisGrpcAsyncIOTransport, + transports.CloudRedisRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CloudRedisClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = cloud_redis.ListInstancesResponse() + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = cloud_redis.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_auth_string_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + call.return_value = cloud_redis.InstanceAuthString() + client.get_instance_auth_string(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upgrade_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.upgrade_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.failover_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CloudRedisAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.Instance( + name="name_value", + display_name="display_name_value", + location_id="location_id_value", + alternative_location_id="alternative_location_id_value", + redis_version="redis_version_value", + reserved_ip_range="reserved_ip_range_value", + secondary_ip_range="secondary_ip_range_value", + host="host_value", + port=453, + current_location_id="current_location_id_value", + state=cloud_redis.Instance.State.CREATING, + status_message="status_message_value", + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network="authorized_network_value", + persistence_iam_identity="persistence_iam_identity_value", + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint="read_endpoint_value", + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + ) + ) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_instance_auth_string_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cloud_redis.InstanceAuthString( + auth_string="auth_string_value", + ) + ) + await client.get_instance_auth_string(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_upgrade_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.upgrade_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_failover_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.failover_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_reschedule_maintenance_empty_call_grpc_asyncio(): + client = CloudRedisAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CloudRedisClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_instances_rest_bad_request(request_type=cloud_redis.ListInstancesRequest): + client = CloudRedisClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = CloudRedisClient( + 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 = cloud_redis.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ListInstancesRequest.pb( + cloud_redis.ListInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.ListInstancesResponse.to_json( + cloud_redis.ListInstancesResponse() + ) + req.return_value.content = return_value + + request = cloud_redis.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.ListInstancesResponse() + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=cloud_redis.GetInstanceRequest): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.Instance( + name="name_value", + display_name="display_name_value", + location_id="location_id_value", + alternative_location_id="alternative_location_id_value", + redis_version="redis_version_value", + reserved_ip_range="reserved_ip_range_value", + secondary_ip_range="secondary_ip_range_value", + host="host_value", + port=453, + current_location_id="current_location_id_value", + state=cloud_redis.Instance.State.CREATING, + status_message="status_message_value", + tier=cloud_redis.Instance.Tier.BASIC, + memory_size_gb=1499, + authorized_network="authorized_network_value", + persistence_iam_identity="persistence_iam_identity_value", + connect_mode=cloud_redis.Instance.ConnectMode.DIRECT_PEERING, + auth_enabled=True, + transit_encryption_mode=cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION, + replica_count=1384, + read_endpoint="read_endpoint_value", + read_endpoint_port=1920, + read_replicas_mode=cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.location_id == "location_id_value" + assert response.alternative_location_id == "alternative_location_id_value" + assert response.redis_version == "redis_version_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + assert response.secondary_ip_range == "secondary_ip_range_value" + assert response.host == "host_value" + assert response.port == 453 + assert response.current_location_id == "current_location_id_value" + assert response.state == cloud_redis.Instance.State.CREATING + assert response.status_message == "status_message_value" + assert response.tier == cloud_redis.Instance.Tier.BASIC + assert response.memory_size_gb == 1499 + assert response.authorized_network == "authorized_network_value" + assert response.persistence_iam_identity == "persistence_iam_identity_value" + assert response.connect_mode == cloud_redis.Instance.ConnectMode.DIRECT_PEERING + assert response.auth_enabled is True + assert ( + response.transit_encryption_mode + == cloud_redis.Instance.TransitEncryptionMode.SERVER_AUTHENTICATION + ) + assert response.replica_count == 1384 + assert response.read_endpoint == "read_endpoint_value" + assert response.read_endpoint_port == 1920 + assert ( + response.read_replicas_mode + == cloud_redis.Instance.ReadReplicasMode.READ_REPLICAS_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.GetInstanceRequest.pb(cloud_redis.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.Instance.to_json(cloud_redis.Instance()) + req.return_value.content = return_value + + request = cloud_redis.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.Instance() + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_auth_string_rest_bad_request( + request_type=cloud_redis.GetInstanceAuthStringRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_instance_auth_string(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.GetInstanceAuthStringRequest, + dict, + ], +) +def test_get_instance_auth_string_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = cloud_redis.InstanceAuthString( + auth_string="auth_string_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = cloud_redis.InstanceAuthString.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_instance_auth_string(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cloud_redis.InstanceAuthString) + assert response.auth_string == "auth_string_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_auth_string_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(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.CloudRedisRestInterceptor, "post_get_instance_auth_string" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_get_instance_auth_string" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.GetInstanceAuthStringRequest.pb( + cloud_redis.GetInstanceAuthStringRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = cloud_redis.InstanceAuthString.to_json( + cloud_redis.InstanceAuthString() + ) + req.return_value.content = return_value + + request = cloud_redis.GetInstanceAuthStringRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_redis.InstanceAuthString() + + client.get_instance_auth_string( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request( + request_type=cloud_redis.CreateInstanceRequest, +): + client = CloudRedisClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "labels": {}, + "location_id": "location_id_value", + "alternative_location_id": "alternative_location_id_value", + "redis_version": "redis_version_value", + "reserved_ip_range": "reserved_ip_range_value", + "secondary_ip_range": "secondary_ip_range_value", + "host": "host_value", + "port": 453, + "current_location_id": "current_location_id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "status_message": "status_message_value", + "redis_configs": {}, + "tier": 1, + "memory_size_gb": 1499, + "authorized_network": "authorized_network_value", + "persistence_iam_identity": "persistence_iam_identity_value", + "connect_mode": 1, + "auth_enabled": True, + "server_ca_certs": [ + { + "serial_number": "serial_number_value", + "cert": "cert_value", + "create_time": {}, + "expire_time": {}, + "sha1_fingerprint": "sha1_fingerprint_value", + } + ], + "transit_encryption_mode": 1, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "description": "description_value", + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + "duration": {"seconds": 751, "nanos": 543}, + } + ], + }, + "maintenance_schedule": { + "start_time": {}, + "end_time": {}, + "can_reschedule": True, + "schedule_deadline_time": {}, + }, + "replica_count": 1384, + "nodes": [{"id": "id_value", "zone": "zone_value"}], + "read_endpoint": "read_endpoint_value", + "read_endpoint_port": 1920, + "read_replicas_mode": 1, + "persistence_config": { + "persistence_mode": 1, + "rdb_snapshot_period": 3, + "rdb_next_snapshot_time": {}, + "rdb_snapshot_start_time": {}, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.CreateInstanceRequest.pb( + cloud_redis.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = cloud_redis.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request( + request_type=cloud_redis.UpdateInstanceRequest, +): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "display_name": "display_name_value", + "labels": {}, + "location_id": "location_id_value", + "alternative_location_id": "alternative_location_id_value", + "redis_version": "redis_version_value", + "reserved_ip_range": "reserved_ip_range_value", + "secondary_ip_range": "secondary_ip_range_value", + "host": "host_value", + "port": 453, + "current_location_id": "current_location_id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "state": 1, + "status_message": "status_message_value", + "redis_configs": {}, + "tier": 1, + "memory_size_gb": 1499, + "authorized_network": "authorized_network_value", + "persistence_iam_identity": "persistence_iam_identity_value", + "connect_mode": 1, + "auth_enabled": True, + "server_ca_certs": [ + { + "serial_number": "serial_number_value", + "cert": "cert_value", + "create_time": {}, + "expire_time": {}, + "sha1_fingerprint": "sha1_fingerprint_value", + } + ], + "transit_encryption_mode": 1, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "description": "description_value", + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + "duration": {"seconds": 751, "nanos": 543}, + } + ], + }, + "maintenance_schedule": { + "start_time": {}, + "end_time": {}, + "can_reschedule": True, + "schedule_deadline_time": {}, + }, + "replica_count": 1384, + "nodes": [{"id": "id_value", "zone": "zone_value"}], + "read_endpoint": "read_endpoint_value", + "read_endpoint_port": 1920, + "read_replicas_mode": 1, + "persistence_config": { + "persistence_mode": 1, + "rdb_snapshot_period": 3, + "rdb_next_snapshot_time": {}, + "rdb_snapshot_start_time": {}, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = cloud_redis.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_instance(request) - unset_fields = transport.upgrade_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "redisVersion", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_upgrade_instance_rest_interceptors(null_interceptor): +def test_update_instance_rest_interceptors(null_interceptor): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7757,6 +8843,7 @@ def test_upgrade_instance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -7764,14 +8851,14 @@ def test_upgrade_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_upgrade_instance" + transports.CloudRedisRestInterceptor, "post_update_instance" ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_upgrade_instance" + transports.CloudRedisRestInterceptor, "pre_update_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.UpgradeInstanceRequest.pb( - cloud_redis.UpgradeInstanceRequest() + pb_message = cloud_redis.UpdateInstanceRequest.pb( + cloud_redis.UpdateInstanceRequest() ) transcode.return_value = { "method": "post", @@ -7780,14 +8867,12 @@ def test_upgrade_instance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = cloud_redis.UpgradeInstanceRequest() + request = cloud_redis.UpdateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -7795,7 +8880,7 @@ def test_upgrade_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.upgrade_instance( + client.update_instance( request, metadata=[ ("key", "val"), @@ -7808,13 +8893,11 @@ def test_upgrade_instance_rest_interceptors(null_interceptor): def test_upgrade_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.UpgradeInstanceRequest + request_type=cloud_redis.UpgradeInstanceRequest, ): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) @@ -7824,244 +8907,50 @@ def test_upgrade_instance_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.upgrade_instance(request) -def test_upgrade_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - redis_version="redis_version_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.upgrade_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:upgrade" - % client.transport._host, - args[1], - ) - - -def test_upgrade_instance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - 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.upgrade_instance( - cloud_redis.UpgradeInstanceRequest(), - name="name_value", - redis_version="redis_version_value", - ) - - -def test_upgrade_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - cloud_redis.ImportInstanceRequest, - dict, - ], -) -def test_import_instance_rest(request_type): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_instance in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.import_instance] = mock_rpc - - request = {} - client.import_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.import_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_import_instance_rest_required_fields( - request_type=cloud_redis.ImportInstanceRequest, -): - transport_class = transports.CloudRedisRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_instance._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() - ).import_instance._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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.import_instance(request) + cloud_redis.UpgradeInstanceRequest, + dict, + ], +) +def test_upgrade_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") -def test_import_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.upgrade_instance(request) - unset_fields = transport.import_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "inputConfig", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_instance_rest_interceptors(null_interceptor): +def test_upgrade_instance_rest_interceptors(null_interceptor): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8069,6 +8958,7 @@ def test_import_instance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -8076,14 +8966,14 @@ def test_import_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_import_instance" + transports.CloudRedisRestInterceptor, "post_upgrade_instance" ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_import_instance" + transports.CloudRedisRestInterceptor, "pre_upgrade_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.ImportInstanceRequest.pb( - cloud_redis.ImportInstanceRequest() + pb_message = cloud_redis.UpgradeInstanceRequest.pb( + cloud_redis.UpgradeInstanceRequest() ) transcode.return_value = { "method": "post", @@ -8092,14 +8982,12 @@ def test_import_instance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = cloud_redis.ImportInstanceRequest() + request = cloud_redis.UpgradeInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8107,7 +8995,7 @@ def test_import_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.import_instance( + client.upgrade_instance( request, metadata=[ ("key", "val"), @@ -8120,13 +9008,11 @@ def test_import_instance_rest_interceptors(null_interceptor): def test_import_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ImportInstanceRequest + request_type=cloud_redis.ImportInstanceRequest, ): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) @@ -8136,93 +9022,25 @@ def test_import_instance_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.import_instance(request) -def test_import_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - input_config=cloud_redis.InputConfig( - gcs_source=cloud_redis.GcsSource(uri="uri_value") - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.import_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:import" - % client.transport._host, - args[1], - ) - - -def test_import_instance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - 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.import_instance( - cloud_redis.ImportInstanceRequest(), - name="name_value", - input_config=cloud_redis.InputConfig( - gcs_source=cloud_redis.GcsSource(uri="uri_value") - ), - ) - - -def test_import_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - cloud_redis.ExportInstanceRequest, + cloud_redis.ImportInstanceRequest, dict, ], ) -def test_export_instance_rest(request_type): +def test_import_instance_rest_call_success(request_type): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -8234,150 +9052,20 @@ def test_export_instance_rest(request_type): # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation(name="operations/spam") - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.export_instance in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.export_instance] = mock_rpc - - request = {} - client.export_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.export_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_export_instance_rest_required_fields( - request_type=cloud_redis.ExportInstanceRequest, -): - transport_class = transports.CloudRedisRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).export_instance._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() - ).export_instance._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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.export_instance(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_export_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_instance(request) - unset_fields = transport.export_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "outputConfig", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_instance_rest_interceptors(null_interceptor): +def test_import_instance_rest_interceptors(null_interceptor): transport = transports.CloudRedisRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8385,6 +9073,7 @@ def test_export_instance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -8392,14 +9081,14 @@ def test_export_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.CloudRedisRestInterceptor, "post_export_instance" + transports.CloudRedisRestInterceptor, "post_import_instance" ) as post, mock.patch.object( - transports.CloudRedisRestInterceptor, "pre_export_instance" + transports.CloudRedisRestInterceptor, "pre_import_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = cloud_redis.ExportInstanceRequest.pb( - cloud_redis.ExportInstanceRequest() + pb_message = cloud_redis.ImportInstanceRequest.pb( + cloud_redis.ImportInstanceRequest() ) transcode.return_value = { "method": "post", @@ -8408,14 +9097,12 @@ def test_export_instance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = cloud_redis.ExportInstanceRequest() + request = cloud_redis.ImportInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8423,7 +9110,7 @@ def test_export_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.export_instance( + client.import_instance( request, metadata=[ ("key", "val"), @@ -8436,13 +9123,11 @@ def test_export_instance_rest_interceptors(null_interceptor): def test_export_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.ExportInstanceRequest + request_type=cloud_redis.ExportInstanceRequest, ): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) @@ -8452,93 +9137,25 @@ def test_export_instance_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.export_instance(request) -def test_export_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - output_config=cloud_redis.OutputConfig( - gcs_destination=cloud_redis.GcsDestination(uri="uri_value") - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.export_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:export" - % client.transport._host, - args[1], - ) - - -def test_export_instance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - 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.export_instance( - cloud_redis.ExportInstanceRequest(), - name="name_value", - output_config=cloud_redis.OutputConfig( - gcs_destination=cloud_redis.GcsDestination(uri="uri_value") - ), - ) - - -def test_export_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - cloud_redis.FailoverInstanceRequest, + cloud_redis.ExportInstanceRequest, dict, ], ) -def test_failover_instance_rest(request_type): +def test_export_instance_rest_call_success(request_type): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -8551,139 +9168,130 @@ def test_failover_instance_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.export_instance(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_failover_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + json_return_value = json_format.MessageToJson(return_value) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.failover_instance in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_instance_rest_interceptors(null_interceptor): + transport = transports.CloudRedisRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudRedisRestInterceptor(), + ) + client = CloudRedisClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CloudRedisRestInterceptor, "post_export_instance" + ) as post, mock.patch.object( + transports.CloudRedisRestInterceptor, "pre_export_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_redis.ExportInstanceRequest.pb( + cloud_redis.ExportInstanceRequest() ) - client._transport._wrapped_methods[ - client._transport.failover_instance - ] = mock_rpc - - request = {} - client.failover_instance(request) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = cloud_redis.ExportInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.failover_instance(request) + client.export_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_failover_instance_rest_required_fields( +def test_failover_instance_rest_bad_request( request_type=cloud_redis.FailoverInstanceRequest, ): - transport_class = transports.CloudRedisRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._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() - ).failover_instance._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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.failover_instance(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.failover_instance(request) +@pytest.mark.parametrize( + "request_type", + [ + cloud_redis.FailoverInstanceRequest, + dict, + ], +) +def test_failover_instance_rest_call_success(request_type): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") -def test_failover_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.failover_instance(request) - unset_fields = transport.failover_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -8695,6 +9303,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -8718,12 +9327,10 @@ def test_failover_instance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = cloud_redis.FailoverInstanceRequest() metadata = [ @@ -8745,14 +9352,12 @@ def test_failover_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_failover_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.FailoverInstanceRequest +def test_delete_instance_rest_bad_request( + request_type=cloud_redis.DeleteInstanceRequest, ): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) @@ -8762,76 +9367,13 @@ def test_failover_instance_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.failover_instance(request) - - -def test_failover_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.failover_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}:failover" - % client.transport._host, - args[1], - ) - - -def test_failover_instance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - 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.failover_instance( - cloud_redis.FailoverInstanceRequest(), - name="name_value", - data_protection_mode=cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS, - ) - - -def test_failover_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.delete_instance(request) @pytest.mark.parametrize( @@ -8841,10 +9383,9 @@ def test_failover_instance_rest_error(): dict, ], ) -def test_delete_instance_rest(request_type): +def test_delete_instance_rest_call_success(request_type): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -8856,137 +9397,16 @@ def test_delete_instance_rest(request_type): # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation(name="operations/spam") - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_instance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc - - request = {} - client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_instance_rest_required_fields( - request_type=cloud_redis.DeleteInstanceRequest, -): - transport_class = transports.CloudRedisRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._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() - ).delete_instance._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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_instance(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_delete_instance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -8998,6 +9418,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9021,12 +9442,10 @@ def test_delete_instance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = cloud_redis.DeleteInstanceRequest() metadata = [ @@ -9048,14 +9467,12 @@ def test_delete_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.DeleteInstanceRequest +def test_reschedule_maintenance_rest_bad_request( + request_type=cloud_redis.RescheduleMaintenanceRequest, ): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) @@ -9065,74 +9482,13 @@ def test_delete_instance_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_instance(request) - - -def test_delete_instance_rest_flattened(): - client = CloudRedisClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.delete_instance(**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/v1beta1/{name=projects/*/locations/*/instances/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_instance_rest_flattened_error(transport: str = "rest"): - client = CloudRedisClient( - 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.delete_instance( - cloud_redis.DeleteInstanceRequest(), - name="name_value", - ) - - -def test_delete_instance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.reschedule_maintenance(request) @pytest.mark.parametrize( @@ -9142,10 +9498,9 @@ def test_delete_instance_rest_error(): dict, ], ) -def test_reschedule_maintenance_rest(request_type): +def test_reschedule_maintenance_rest_call_success(request_type): client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9158,150 +9513,15 @@ def test_reschedule_maintenance_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.reschedule_maintenance(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_reschedule_maintenance_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.reschedule_maintenance - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.reschedule_maintenance - ] = mock_rpc - - request = {} - client.reschedule_maintenance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.reschedule_maintenance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_reschedule_maintenance_rest_required_fields( - request_type=cloud_redis.RescheduleMaintenanceRequest, -): - transport_class = transports.CloudRedisRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).reschedule_maintenance._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() - ).reschedule_maintenance._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 = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.reschedule_maintenance(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_reschedule_maintenance_rest_unset_required_fields(): - transport = transports.CloudRedisRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "rescheduleType", - ) - ) - ) + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9313,6 +9533,7 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): else transports.CloudRedisRestInterceptor(), ) client = CloudRedisClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9336,12 +9557,10 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = cloud_redis.RescheduleMaintenanceRequest() metadata = [ @@ -9359,205 +9578,258 @@ def test_reschedule_maintenance_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() + pre.assert_called_once() + post.assert_called_once() + + +def test_initialize_client_w_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_instances_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ListInstancesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceRequest() + + assert args[0] == request_msg -def test_reschedule_maintenance_rest_bad_request( - transport: str = "rest", request_type=cloud_redis.RescheduleMaintenanceRequest -): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_instance_auth_string_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_instance_auth_string), "__call__" + ) as call: + client.get_instance_auth_string(request=None) - # 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.reschedule_maintenance(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.GetInstanceAuthStringRequest() + assert args[0] == request_msg -def test_reschedule_maintenance_rest_flattened(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_instance_empty_call_rest(): client = CloudRedisClient( 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.CreateInstanceRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.reschedule_maintenance(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_instance_empty_call_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v1beta1/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpdateInstanceRequest() -def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upgrade_instance_empty_call_rest(): client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.reschedule_maintenance( - cloud_redis.RescheduleMaintenanceRequest(), - name="name_value", - reschedule_type=cloud_redis.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, - schedule_time=timestamp_pb2.Timestamp(seconds=751), - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.upgrade_instance), "__call__") as call: + client.upgrade_instance(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.UpgradeInstanceRequest() -def test_reschedule_maintenance_rest_error(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CloudRedisGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_instance_empty_call_rest(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_instance), "__call__") as call: + client.import_instance(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudRedisGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ImportInstanceRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.CloudRedisGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_instance_empty_call_rest(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CloudRedisClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_instance), "__call__") as call: + client.export_instance(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.ExportInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_instance_empty_call_rest(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CloudRedisClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: + client.failover_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.FailoverInstanceRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudRedisGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_instance_empty_call_rest(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CloudRedisGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.DeleteInstanceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_reschedule_maintenance_empty_call_rest(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + client.reschedule_maintenance(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudRedisGrpcTransport, - transports.CloudRedisGrpcAsyncIOTransport, - transports.CloudRedisRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cloud_redis.RescheduleMaintenanceRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CloudRedisClient.get_transport_class(transport_name)( + +def test_cloud_redis_rest_lro_client(): + client = CloudRedisClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -9801,23 +10073,6 @@ def test_cloud_redis_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_cloud_redis_rest_lro_client(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -10220,36 +10475,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = CloudRedisAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CloudRedisClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = CloudRedisClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/async_client.py index 3bd2386561ef..b27e74377692 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/async_client.py @@ -1790,11 +1790,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/client.py index ff68a11427df..23f70cb6240e 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/client.py @@ -2201,11 +2201,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/README.rst new file mode 100644 index 000000000000..24b2682b8116 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`FoldersTransport` is the ABC for all transports. +- public child `FoldersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `FoldersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseFoldersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `FoldersRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/base.py index d10c59660f03..9a68d2bd58fa 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/base.py @@ -216,6 +216,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py index 623600c1ea80..54d509dcd97a 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -669,7 +673,7 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_folder: gapic_v1.method_async.wrap_method( + self.get_folder: self._wrap_method( self.get_folder, default_retry=retries.AsyncRetry( initial=0.1, @@ -683,7 +687,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.list_folders: gapic_v1.method_async.wrap_method( + self.list_folders: self._wrap_method( self.list_folders, default_retry=retries.AsyncRetry( initial=0.1, @@ -697,37 +701,37 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.search_folders: gapic_v1.method_async.wrap_method( + self.search_folders: self._wrap_method( self.search_folders, default_timeout=60.0, client_info=client_info, ), - self.create_folder: gapic_v1.method_async.wrap_method( + self.create_folder: self._wrap_method( self.create_folder, default_timeout=60.0, client_info=client_info, ), - self.update_folder: gapic_v1.method_async.wrap_method( + self.update_folder: self._wrap_method( self.update_folder, default_timeout=60.0, client_info=client_info, ), - self.move_folder: gapic_v1.method_async.wrap_method( + self.move_folder: self._wrap_method( self.move_folder, default_timeout=60.0, client_info=client_info, ), - self.delete_folder: gapic_v1.method_async.wrap_method( + self.delete_folder: self._wrap_method( self.delete_folder, default_timeout=60.0, client_info=client_info, ), - self.undelete_folder: gapic_v1.method_async.wrap_method( + self.undelete_folder: self._wrap_method( self.undelete_folder, default_timeout=60.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_retry=retries.AsyncRetry( initial=0.1, @@ -741,21 +745,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=60.0, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest.py index 05d89b854c45..986cd6a4a523 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import folders + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseFoldersRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import folders - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import FoldersTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -431,8 +421,8 @@ class FoldersRestStub: _interceptor: FoldersRestInterceptor -class FoldersRestTransport(FoldersTransport): - """REST backend transport for Folders. +class FoldersRestTransport(_BaseFoldersRestTransport): + """REST backend synchronous transport for Folders. Manages Cloud Platform folder resources. Folders can be used to organize the resources under an @@ -444,7 +434,6 @@ class FoldersRestTransport(FoldersTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -498,21 +487,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -558,19 +538,32 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateFolder(FoldersRestStub): + class _CreateFolder(_BaseFoldersRestTransport._BaseCreateFolder, FoldersRestStub): def __hash__(self): - return hash("CreateFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.CreateFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -599,45 +592,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/folders", - "body": "folder", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseCreateFolder._get_http_options() + ) request, metadata = self._interceptor.pre_create_folder(request, metadata) - pb_request = folders.CreateFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseCreateFolder._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseCreateFolder._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseCreateFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._CreateFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -651,19 +635,31 @@ def __call__( resp = self._interceptor.post_create_folder(resp) return resp - class _DeleteFolder(FoldersRestStub): + class _DeleteFolder(_BaseFoldersRestTransport._BaseDeleteFolder, FoldersRestStub): def __hash__(self): - return hash("DeleteFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.DeleteFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -692,38 +688,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=folders/*}", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseDeleteFolder._get_http_options() + ) request, metadata = self._interceptor.pre_delete_folder(request, metadata) - pb_request = folders.DeleteFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseFoldersRestTransport._BaseDeleteFolder._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseDeleteFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = FoldersRestTransport._DeleteFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -737,19 +726,31 @@ def __call__( resp = self._interceptor.post_delete_folder(resp) return resp - class _GetFolder(FoldersRestStub): + class _GetFolder(_BaseFoldersRestTransport._BaseGetFolder, FoldersRestStub): def __hash__(self): - return hash("GetFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.GetFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -778,38 +779,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=folders/*}", - }, - ] + http_options = _BaseFoldersRestTransport._BaseGetFolder._get_http_options() request, metadata = self._interceptor.pre_get_folder(request, metadata) - pb_request = folders.GetFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseFoldersRestTransport._BaseGetFolder._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseGetFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = FoldersRestTransport._GetFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -825,19 +817,32 @@ def __call__( resp = self._interceptor.post_get_folder(resp) return resp - class _GetIamPolicy(FoldersRestStub): + class _GetIamPolicy(_BaseFoldersRestTransport._BaseGetIamPolicy, FoldersRestStub): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -938,45 +943,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=folders/*}:getIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseGetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -992,21 +988,31 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _ListFolders(FoldersRestStub): + class _ListFolders(_BaseFoldersRestTransport._BaseListFolders, FoldersRestStub): def __hash__(self): - return hash("ListFolders") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("FoldersRestTransport.ListFolders") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1032,38 +1038,31 @@ def __call__( The ListFolders response message. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/folders", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseListFolders._get_http_options() + ) request, metadata = self._interceptor.pre_list_folders(request, metadata) - pb_request = folders.ListFoldersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseFoldersRestTransport._BaseListFolders._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseListFolders._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = FoldersRestTransport._ListFolders._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1079,19 +1078,32 @@ def __call__( resp = self._interceptor.post_list_folders(resp) return resp - class _MoveFolder(FoldersRestStub): + class _MoveFolder(_BaseFoldersRestTransport._BaseMoveFolder, FoldersRestStub): def __hash__(self): - return hash("MoveFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.MoveFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1120,45 +1132,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{name=folders/*}:move", - "body": "*", - }, - ] + http_options = _BaseFoldersRestTransport._BaseMoveFolder._get_http_options() request, metadata = self._interceptor.pre_move_folder(request, metadata) - pb_request = folders.MoveFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseMoveFolder._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseMoveFolder._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseMoveFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._MoveFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1172,9 +1173,31 @@ def __call__( resp = self._interceptor.post_move_folder(resp) return resp - class _SearchFolders(FoldersRestStub): + class _SearchFolders(_BaseFoldersRestTransport._BaseSearchFolders, FoldersRestStub): def __hash__(self): - return hash("SearchFolders") + return hash("FoldersRestTransport.SearchFolders") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1203,37 +1226,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/folders:search", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseSearchFolders._get_http_options() + ) request, metadata = self._interceptor.pre_search_folders(request, metadata) - pb_request = folders.SearchFoldersRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseFoldersRestTransport._BaseSearchFolders._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseSearchFolders._get_query_params_json( + transcoded_request ) ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = FoldersRestTransport._SearchFolders._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1249,19 +1266,32 @@ def __call__( resp = self._interceptor.post_search_folders(resp) return resp - class _SetIamPolicy(FoldersRestStub): + class _SetIamPolicy(_BaseFoldersRestTransport._BaseSetIamPolicy, FoldersRestStub): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1362,45 +1392,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=folders/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1416,19 +1437,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(FoldersRestStub): + class _TestIamPermissions( + _BaseFoldersRestTransport._BaseTestIamPermissions, FoldersRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1454,47 +1490,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=folders/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseFoldersRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseFoldersRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1510,19 +1533,34 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UndeleteFolder(FoldersRestStub): + class _UndeleteFolder( + _BaseFoldersRestTransport._BaseUndeleteFolder, FoldersRestStub + ): def __hash__(self): - return hash("UndeleteFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("FoldersRestTransport.UndeleteFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1551,45 +1589,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{name=folders/*}:undelete", - "body": "*", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseUndeleteFolder._get_http_options() + ) request, metadata = self._interceptor.pre_undelete_folder(request, metadata) - pb_request = folders.UndeleteFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseUndeleteFolder._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseUndeleteFolder._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseUndeleteFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._UndeleteFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1603,21 +1632,32 @@ def __call__( resp = self._interceptor.post_undelete_folder(resp) return resp - class _UpdateFolder(FoldersRestStub): + class _UpdateFolder(_BaseFoldersRestTransport._BaseUpdateFolder, FoldersRestStub): def __hash__(self): - return hash("UpdateFolder") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } - - @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 - } + return hash("FoldersRestTransport.UpdateFolder") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1653,45 +1693,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v3/{folder.name=folders/*}", - "body": "folder", - }, - ] + http_options = ( + _BaseFoldersRestTransport._BaseUpdateFolder._get_http_options() + ) request, metadata = self._interceptor.pre_update_folder(request, metadata) - pb_request = folders.UpdateFolderRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseFoldersRestTransport._BaseUpdateFolder._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseFoldersRestTransport._BaseUpdateFolder._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseFoldersRestTransport._BaseUpdateFolder._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = FoldersRestTransport._UpdateFolder._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1798,7 +1829,32 @@ def update_folder( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(FoldersRestStub): + class _GetOperation(_BaseFoldersRestTransport._BaseGetOperation, FoldersRestStub): + def __hash__(self): + return hash("FoldersRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1822,32 +1878,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseFoldersRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseFoldersRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseFoldersRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = FoldersRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1855,8 +1910,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest_base.py new file mode 100644 index 000000000000..11411ee953ce --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/folders/transports/rest_base.py @@ -0,0 +1,695 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import folders + +from .base import DEFAULT_CLIENT_INFO, FoldersTransport + + +class _BaseFoldersRestTransport(FoldersTransport): + """Base REST backend transport for Folders. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/folders", + "body": "folder", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.CreateFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseCreateFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=folders/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.DeleteFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseDeleteFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=folders/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.GetFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseGetFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=folders/*}:getIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFolders: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/folders", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.ListFoldersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseListFolders._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMoveFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=folders/*}:move", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.MoveFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseMoveFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchFolders: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/folders:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.SearchFoldersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=folders/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=folders/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=folders/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.UndeleteFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseUndeleteFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateFolder: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{folder.name=folders/*}", + "body": "folder", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = folders.UpdateFolderRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFoldersRestTransport._BaseUpdateFolder._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseFoldersRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/async_client.py index c0f2b3e3ea9d..f64be9dc0123 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/async_client.py @@ -942,11 +942,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/client.py index 884cca15464b..f538d52502c3 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/client.py @@ -1366,11 +1366,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/README.rst new file mode 100644 index 000000000000..cdabe7ebc433 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OrganizationsTransport` is the ABC for all transports. +- public child `OrganizationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OrganizationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOrganizationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OrganizationsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/base.py index 3f9358f9fdd1..23315a19e9f7 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/base.py @@ -177,6 +177,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py index b24b2f828d56..23a93093f608 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -408,7 +412,7 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_organization: gapic_v1.method_async.wrap_method( + self.get_organization: self._wrap_method( self.get_organization, default_retry=retries.AsyncRetry( initial=0.1, @@ -422,12 +426,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.search_organizations: gapic_v1.method_async.wrap_method( + self.search_organizations: self._wrap_method( self.search_organizations, default_timeout=60.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_retry=retries.AsyncRetry( initial=0.1, @@ -441,21 +445,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=60.0, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py index 747947def0c9..26f230cde9d9 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest.py @@ -16,35 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import organizations + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseOrganizationsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import organizations - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import OrganizationsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -255,8 +251,8 @@ class OrganizationsRestStub: _interceptor: OrganizationsRestInterceptor -class OrganizationsRestTransport(OrganizationsTransport): - """REST backend transport for Organizations. +class OrganizationsRestTransport(_BaseOrganizationsRestTransport): + """REST backend synchronous transport for Organizations. Allows users to manage their organization resources. @@ -265,7 +261,6 @@ class OrganizationsRestTransport(OrganizationsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -319,21 +314,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -344,19 +330,34 @@ def __init__( self._interceptor = interceptor or OrganizationsRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetIamPolicy(OrganizationsRestStub): + class _GetIamPolicy( + _BaseOrganizationsRestTransport._BaseGetIamPolicy, OrganizationsRestStub + ): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OrganizationsRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -457,45 +458,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=organizations/*}:getIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseOrganizationsRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOrganizationsRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOrganizationsRestTransport._BaseGetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOrganizationsRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OrganizationsRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -511,19 +499,33 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetOrganization(OrganizationsRestStub): + class _GetOrganization( + _BaseOrganizationsRestTransport._BaseGetOrganization, OrganizationsRestStub + ): def __hash__(self): - return hash("GetOrganization") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OrganizationsRestTransport.GetOrganization") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -555,40 +557,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=organizations/*}", - }, - ] + http_options = ( + _BaseOrganizationsRestTransport._BaseGetOrganization._get_http_options() + ) request, metadata = self._interceptor.pre_get_organization( request, metadata ) - pb_request = organizations.GetOrganizationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOrganizationsRestTransport._BaseGetOrganization._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOrganizationsRestTransport._BaseGetOrganization._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = OrganizationsRestTransport._GetOrganization._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -604,9 +595,33 @@ def __call__( resp = self._interceptor.post_get_organization(resp) return resp - class _SearchOrganizations(OrganizationsRestStub): + class _SearchOrganizations( + _BaseOrganizationsRestTransport._BaseSearchOrganizations, OrganizationsRestStub + ): def __hash__(self): - return hash("SearchOrganizations") + return hash("OrganizationsRestTransport.SearchOrganizations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -634,39 +649,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/organizations:search", - }, - ] + http_options = ( + _BaseOrganizationsRestTransport._BaseSearchOrganizations._get_http_options() + ) request, metadata = self._interceptor.pre_search_organizations( request, metadata ) - pb_request = organizations.SearchOrganizationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOrganizationsRestTransport._BaseSearchOrganizations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOrganizationsRestTransport._BaseSearchOrganizations._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = OrganizationsRestTransport._SearchOrganizations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -682,19 +687,34 @@ def __call__( resp = self._interceptor.post_search_organizations(resp) return resp - class _SetIamPolicy(OrganizationsRestStub): + class _SetIamPolicy( + _BaseOrganizationsRestTransport._BaseSetIamPolicy, OrganizationsRestStub + ): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OrganizationsRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -795,45 +815,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=organizations/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseOrganizationsRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOrganizationsRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOrganizationsRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOrganizationsRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OrganizationsRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -849,19 +856,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(OrganizationsRestStub): + class _TestIamPermissions( + _BaseOrganizationsRestTransport._BaseTestIamPermissions, OrganizationsRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("OrganizationsRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -887,47 +909,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=organizations/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseOrganizationsRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseOrganizationsRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseOrganizationsRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseOrganizationsRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = OrganizationsRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -993,7 +1002,34 @@ def test_iam_permissions( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(OrganizationsRestStub): + class _GetOperation( + _BaseOrganizationsRestTransport._BaseGetOperation, OrganizationsRestStub + ): + def __hash__(self): + return hash("OrganizationsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1017,32 +1053,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseOrganizationsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseOrganizationsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseOrganizationsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = OrganizationsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1050,8 +1081,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest_base.py new file mode 100644 index 000000000000..99cb3abcbbfe --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/organizations/transports/rest_base.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import organizations + +from .base import DEFAULT_CLIENT_INFO, OrganizationsTransport + + +class _BaseOrganizationsRestTransport(OrganizationsTransport): + """Base REST backend transport for Organizations. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=organizations/*}:getIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationsRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOrganization: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=organizations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = organizations.GetOrganizationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationsRestTransport._BaseGetOrganization._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchOrganizations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/organizations:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = organizations.SearchOrganizationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=organizations/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationsRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=organizations/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationsRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseOrganizationsRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/async_client.py index d158bd99239e..258d67302211 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/async_client.py @@ -1846,11 +1846,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/client.py index 7cbbc6758094..36fe9c4cdd63 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/client.py @@ -2257,11 +2257,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/README.rst new file mode 100644 index 000000000000..e832f0d51f32 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProjectsTransport` is the ABC for all transports. +- public child `ProjectsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProjectsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProjectsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProjectsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/base.py index 5c9294b1bee8..fae261b44d8d 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/base.py @@ -216,6 +216,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py index ad5911afe672..db3bfa44e52c 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -697,7 +701,7 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_project: gapic_v1.method_async.wrap_method( + self.get_project: self._wrap_method( self.get_project, default_retry=retries.AsyncRetry( initial=0.1, @@ -711,7 +715,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.list_projects: gapic_v1.method_async.wrap_method( + self.list_projects: self._wrap_method( self.list_projects, default_retry=retries.AsyncRetry( initial=0.1, @@ -725,37 +729,37 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.search_projects: gapic_v1.method_async.wrap_method( + self.search_projects: self._wrap_method( self.search_projects, default_timeout=60.0, client_info=client_info, ), - self.create_project: gapic_v1.method_async.wrap_method( + self.create_project: self._wrap_method( self.create_project, default_timeout=60.0, client_info=client_info, ), - self.update_project: gapic_v1.method_async.wrap_method( + self.update_project: self._wrap_method( self.update_project, default_timeout=60.0, client_info=client_info, ), - self.move_project: gapic_v1.method_async.wrap_method( + self.move_project: self._wrap_method( self.move_project, default_timeout=60.0, client_info=client_info, ), - self.delete_project: gapic_v1.method_async.wrap_method( + self.delete_project: self._wrap_method( self.delete_project, default_timeout=60.0, client_info=client_info, ), - self.undelete_project: gapic_v1.method_async.wrap_method( + self.undelete_project: self._wrap_method( self.undelete_project, default_timeout=60.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_retry=retries.AsyncRetry( initial=0.1, @@ -769,21 +773,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=60.0, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest.py index fb19f4525899..6f2126d31c44 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import projects + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProjectsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import projects - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProjectsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -439,8 +429,8 @@ class ProjectsRestStub: _interceptor: ProjectsRestInterceptor -class ProjectsRestTransport(ProjectsTransport): - """REST backend transport for Projects. +class ProjectsRestTransport(_BaseProjectsRestTransport): + """REST backend synchronous transport for Projects. Manages Google Cloud Projects. @@ -449,7 +439,6 @@ class ProjectsRestTransport(ProjectsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -503,21 +492,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -563,19 +543,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateProject(ProjectsRestStub): + class _CreateProject( + _BaseProjectsRestTransport._BaseCreateProject, ProjectsRestStub + ): def __hash__(self): - return hash("CreateProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.CreateProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -606,45 +601,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/projects", - "body": "project", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseCreateProject._get_http_options() + ) request, metadata = self._interceptor.pre_create_project(request, metadata) - pb_request = projects.CreateProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseCreateProject._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseCreateProject._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseCreateProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._CreateProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -658,19 +644,33 @@ def __call__( resp = self._interceptor.post_create_project(resp) return resp - class _DeleteProject(ProjectsRestStub): + class _DeleteProject( + _BaseProjectsRestTransport._BaseDeleteProject, ProjectsRestStub + ): def __hash__(self): - return hash("DeleteProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.DeleteProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -700,38 +700,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=projects/*}", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseDeleteProject._get_http_options() + ) request, metadata = self._interceptor.pre_delete_project(request, metadata) - pb_request = projects.DeleteProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseProjectsRestTransport._BaseDeleteProject._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseDeleteProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectsRestTransport._DeleteProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -745,19 +738,32 @@ def __call__( resp = self._interceptor.post_delete_project(resp) return resp - class _GetIamPolicy(ProjectsRestStub): + class _GetIamPolicy(_BaseProjectsRestTransport._BaseGetIamPolicy, ProjectsRestStub): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -858,45 +864,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=projects/*}:getIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseGetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -912,19 +909,31 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetProject(ProjectsRestStub): + class _GetProject(_BaseProjectsRestTransport._BaseGetProject, ProjectsRestStub): def __hash__(self): - return hash("GetProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.GetProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -956,38 +965,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=projects/*}", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseGetProject._get_http_options() + ) request, metadata = self._interceptor.pre_get_project(request, metadata) - pb_request = projects.GetProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseProjectsRestTransport._BaseGetProject._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseGetProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectsRestTransport._GetProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1003,21 +1005,31 @@ def __call__( resp = self._interceptor.post_get_project(resp) return resp - class _ListProjects(ProjectsRestStub): + class _ListProjects(_BaseProjectsRestTransport._BaseListProjects, ProjectsRestStub): def __hash__(self): - return hash("ListProjects") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("ProjectsRestTransport.ListProjects") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1056,38 +1068,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/projects", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseListProjects._get_http_options() + ) request, metadata = self._interceptor.pre_list_projects(request, metadata) - pb_request = projects.ListProjectsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseProjectsRestTransport._BaseListProjects._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseListProjects._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectsRestTransport._ListProjects._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1103,19 +1108,32 @@ def __call__( resp = self._interceptor.post_list_projects(resp) return resp - class _MoveProject(ProjectsRestStub): + class _MoveProject(_BaseProjectsRestTransport._BaseMoveProject, ProjectsRestStub): def __hash__(self): - return hash("MoveProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.MoveProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1146,45 +1164,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{name=projects/*}:move", - "body": "*", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseMoveProject._get_http_options() + ) request, metadata = self._interceptor.pre_move_project(request, metadata) - pb_request = projects.MoveProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseMoveProject._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseMoveProject._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseMoveProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._MoveProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1198,9 +1207,33 @@ def __call__( resp = self._interceptor.post_move_project(resp) return resp - class _SearchProjects(ProjectsRestStub): + class _SearchProjects( + _BaseProjectsRestTransport._BaseSearchProjects, ProjectsRestStub + ): def __hash__(self): - return hash("SearchProjects") + return hash("ProjectsRestTransport.SearchProjects") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1235,37 +1268,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/projects:search", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseSearchProjects._get_http_options() + ) request, metadata = self._interceptor.pre_search_projects(request, metadata) - pb_request = projects.SearchProjectsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseProjectsRestTransport._BaseSearchProjects._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseSearchProjects._get_query_params_json( + transcoded_request ) ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = ProjectsRestTransport._SearchProjects._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1281,19 +1308,32 @@ def __call__( resp = self._interceptor.post_search_projects(resp) return resp - class _SetIamPolicy(ProjectsRestStub): + class _SetIamPolicy(_BaseProjectsRestTransport._BaseSetIamPolicy, ProjectsRestStub): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1394,45 +1434,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=projects/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1448,19 +1479,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(ProjectsRestStub): + class _TestIamPermissions( + _BaseProjectsRestTransport._BaseTestIamPermissions, ProjectsRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1486,47 +1532,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=projects/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectsRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectsRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1542,19 +1575,34 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UndeleteProject(ProjectsRestStub): + class _UndeleteProject( + _BaseProjectsRestTransport._BaseUndeleteProject, ProjectsRestStub + ): def __hash__(self): - return hash("UndeleteProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.UndeleteProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1585,47 +1633,40 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{name=projects/*}:undelete", - "body": "*", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseUndeleteProject._get_http_options() + ) request, metadata = self._interceptor.pre_undelete_project( request, metadata ) - pb_request = projects.UndeleteProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseUndeleteProject._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseProjectsRestTransport._BaseUndeleteProject._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseUndeleteProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._UndeleteProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1639,19 +1680,34 @@ def __call__( resp = self._interceptor.post_undelete_project(resp) return resp - class _UpdateProject(ProjectsRestStub): + class _UpdateProject( + _BaseProjectsRestTransport._BaseUpdateProject, ProjectsRestStub + ): def __hash__(self): - return hash("UpdateProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectsRestTransport.UpdateProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1687,45 +1743,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v3/{project.name=projects/*}", - "body": "project", - }, - ] + http_options = ( + _BaseProjectsRestTransport._BaseUpdateProject._get_http_options() + ) request, metadata = self._interceptor.pre_update_project(request, metadata) - pb_request = projects.UpdateProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseProjectsRestTransport._BaseUpdateProject._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectsRestTransport._BaseUpdateProject._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectsRestTransport._BaseUpdateProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectsRestTransport._UpdateProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1832,7 +1879,32 @@ def update_project( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProjectsRestStub): + class _GetOperation(_BaseProjectsRestTransport._BaseGetOperation, ProjectsRestStub): + def __hash__(self): + return hash("ProjectsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1856,32 +1928,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseProjectsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseProjectsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseProjectsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ProjectsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1889,8 +1960,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest_base.py new file mode 100644 index 000000000000..9ebabfdd45f0 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/rest_base.py @@ -0,0 +1,693 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import projects + +from .base import DEFAULT_CLIENT_INFO, ProjectsTransport + + +class _BaseProjectsRestTransport(ProjectsTransport): + """Base REST backend transport for Projects. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/projects", + "body": "project", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.CreateProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseCreateProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=projects/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.DeleteProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseDeleteProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=projects/*}:getIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=projects/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.GetProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseGetProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProjects: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/projects", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.ListProjectsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseListProjects._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMoveProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*}:move", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.MoveProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseMoveProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSearchProjects: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/projects:search", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.SearchProjectsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=projects/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=projects/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{name=projects/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.UndeleteProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseUndeleteProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{project.name=projects/*}", + "body": "project", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = projects.UpdateProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectsRestTransport._BaseUpdateProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProjectsRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py index 2d881fd4dddc..129b38e5c2a4 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/async_client.py @@ -778,11 +778,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/client.py index 6e886169d9d8..2b78ebd76b19 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/client.py @@ -1220,11 +1220,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/README.rst new file mode 100644 index 000000000000..8d61ae344ed8 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TagBindingsTransport` is the ABC for all transports. +- public child `TagBindingsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TagBindingsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTagBindingsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TagBindingsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py index 2bf05da80824..ec7ce192d1bc 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/base.py @@ -161,6 +161,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py index 231c545f58f5..1736e074e55c 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -382,7 +386,7 @@ def list_effective_tags( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_tag_bindings: gapic_v1.method_async.wrap_method( + self.list_tag_bindings: self._wrap_method( self.list_tag_bindings, default_retry=retries.AsyncRetry( initial=0.1, @@ -396,26 +400,40 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.create_tag_binding: gapic_v1.method_async.wrap_method( + self.create_tag_binding: self._wrap_method( self.create_tag_binding, default_timeout=60.0, client_info=client_info, ), - self.delete_tag_binding: gapic_v1.method_async.wrap_method( + self.delete_tag_binding: self._wrap_method( self.delete_tag_binding, default_timeout=60.0, client_info=client_info, ), - self.list_effective_tags: gapic_v1.method_async.wrap_method( + self.list_effective_tags: self._wrap_method( self.list_effective_tags, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py index 44984607dd9d..0e619e62dc7f 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest.py @@ -16,39 +16,29 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import tag_bindings + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTagBindingsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_bindings - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import TagBindingsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -232,8 +222,8 @@ class TagBindingsRestStub: _interceptor: TagBindingsRestInterceptor -class TagBindingsRestTransport(TagBindingsTransport): - """REST backend transport for TagBindings. +class TagBindingsRestTransport(_BaseTagBindingsRestTransport): + """REST backend synchronous transport for TagBindings. Allow users to create and manage TagBindings between TagValues and different Google Cloud resources throughout the @@ -244,7 +234,6 @@ class TagBindingsRestTransport(TagBindingsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -298,21 +287,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -358,19 +338,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateTagBinding(TagBindingsRestStub): + class _CreateTagBinding( + _BaseTagBindingsRestTransport._BaseCreateTagBinding, TagBindingsRestStub + ): def __hash__(self): - return hash("CreateTagBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagBindingsRestTransport.CreateTagBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -400,47 +395,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/tagBindings", - "body": "tag_binding", - }, - ] + http_options = ( + _BaseTagBindingsRestTransport._BaseCreateTagBinding._get_http_options() + ) request, metadata = self._interceptor.pre_create_tag_binding( request, metadata ) - pb_request = tag_bindings.CreateTagBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseTagBindingsRestTransport._BaseCreateTagBinding._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagBindingsRestTransport._BaseCreateTagBinding._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagBindingsRestTransport._BaseCreateTagBinding._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagBindingsRestTransport._CreateTagBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -454,19 +436,33 @@ def __call__( resp = self._interceptor.post_create_tag_binding(resp) return resp - class _DeleteTagBinding(TagBindingsRestStub): + class _DeleteTagBinding( + _BaseTagBindingsRestTransport._BaseDeleteTagBinding, TagBindingsRestStub + ): def __hash__(self): - return hash("DeleteTagBinding") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagBindingsRestTransport.DeleteTagBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -496,40 +492,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=tagBindings/**}", - }, - ] + http_options = ( + _BaseTagBindingsRestTransport._BaseDeleteTagBinding._get_http_options() + ) request, metadata = self._interceptor.pre_delete_tag_binding( request, metadata ) - pb_request = tag_bindings.DeleteTagBindingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseTagBindingsRestTransport._BaseDeleteTagBinding._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagBindingsRestTransport._BaseDeleteTagBinding._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagBindingsRestTransport._DeleteTagBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -543,21 +528,33 @@ def __call__( resp = self._interceptor.post_delete_tag_binding(resp) return resp - class _ListEffectiveTags(TagBindingsRestStub): + class _ListEffectiveTags( + _BaseTagBindingsRestTransport._BaseListEffectiveTags, TagBindingsRestStub + ): def __hash__(self): - return hash("ListEffectiveTags") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("TagBindingsRestTransport.ListEffectiveTags") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -584,40 +581,29 @@ def __call__( The response of ListEffectiveTags. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/effectiveTags", - }, - ] + http_options = ( + _BaseTagBindingsRestTransport._BaseListEffectiveTags._get_http_options() + ) request, metadata = self._interceptor.pre_list_effective_tags( request, metadata ) - pb_request = tag_bindings.ListEffectiveTagsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseTagBindingsRestTransport._BaseListEffectiveTags._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagBindingsRestTransport._BaseListEffectiveTags._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagBindingsRestTransport._ListEffectiveTags._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -633,21 +619,33 @@ def __call__( resp = self._interceptor.post_list_effective_tags(resp) return resp - class _ListTagBindings(TagBindingsRestStub): + class _ListTagBindings( + _BaseTagBindingsRestTransport._BaseListTagBindings, TagBindingsRestStub + ): def __hash__(self): - return hash("ListTagBindings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("TagBindingsRestTransport.ListTagBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -674,40 +672,29 @@ def __call__( The ListTagBindings response. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/tagBindings", - }, - ] + http_options = ( + _BaseTagBindingsRestTransport._BaseListTagBindings._get_http_options() + ) request, metadata = self._interceptor.pre_list_tag_bindings( request, metadata ) - pb_request = tag_bindings.ListTagBindingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseTagBindingsRestTransport._BaseListTagBindings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagBindingsRestTransport._BaseListTagBindings._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagBindingsRestTransport._ListTagBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -763,7 +750,34 @@ def list_tag_bindings( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(TagBindingsRestStub): + class _GetOperation( + _BaseTagBindingsRestTransport._BaseGetOperation, TagBindingsRestStub + ): + def __hash__(self): + return hash("TagBindingsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -787,32 +801,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseTagBindingsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagBindingsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTagBindingsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TagBindingsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -820,8 +833,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest_base.py new file mode 100644 index 000000000000..cb3ab25f4a41 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_bindings/transports/rest_base.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import tag_bindings + +from .base import DEFAULT_CLIENT_INFO, TagBindingsTransport + + +class _BaseTagBindingsRestTransport(TagBindingsTransport): + """Base REST backend transport for TagBindings. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateTagBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/tagBindings", + "body": "tag_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_bindings.CreateTagBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagBindingsRestTransport._BaseCreateTagBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTagBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=tagBindings/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_bindings.DeleteTagBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagBindingsRestTransport._BaseDeleteTagBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEffectiveTags: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/effectiveTags", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_bindings.ListEffectiveTagsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagBindingsRestTransport._BaseListEffectiveTags._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTagBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/tagBindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_bindings.ListTagBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagBindingsRestTransport._BaseListTagBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseTagBindingsRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/async_client.py index d144341f0aa2..ddb2a1c02940 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/async_client.py @@ -674,11 +674,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/client.py index 286b17669188..3257d1611c9c 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/client.py @@ -1099,11 +1099,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/README.rst new file mode 100644 index 000000000000..40f8e3811d7e --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TagHoldsTransport` is the ABC for all transports. +- public child `TagHoldsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TagHoldsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTagHoldsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TagHoldsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/base.py index 0a640e76a2ea..3ba3ebc92b3a 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/base.py @@ -147,6 +147,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/grpc_asyncio.py index 37e69bc46ede..2e441f976475 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -349,26 +353,40 @@ def list_tag_holds( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_tag_hold: gapic_v1.method_async.wrap_method( + self.create_tag_hold: self._wrap_method( self.create_tag_hold, default_timeout=None, client_info=client_info, ), - self.delete_tag_hold: gapic_v1.method_async.wrap_method( + self.delete_tag_hold: self._wrap_method( self.delete_tag_hold, default_timeout=None, client_info=client_info, ), - self.list_tag_holds: gapic_v1.method_async.wrap_method( + self.list_tag_holds: self._wrap_method( self.list_tag_holds, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest.py index a93cb4beafb2..a1c96a2e95c9 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest.py @@ -16,39 +16,29 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import tag_holds + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTagHoldsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_holds - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import TagHoldsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -201,8 +191,8 @@ class TagHoldsRestStub: _interceptor: TagHoldsRestInterceptor -class TagHoldsRestTransport(TagHoldsTransport): - """REST backend transport for TagHolds. +class TagHoldsRestTransport(_BaseTagHoldsRestTransport): + """REST backend synchronous transport for TagHolds. Allow users to create and manage TagHolds for TagValues. TagHolds represent the use of a Tag Value that is not captured @@ -216,7 +206,6 @@ class TagHoldsRestTransport(TagHoldsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -270,21 +259,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -330,19 +310,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateTagHold(TagHoldsRestStub): + class _CreateTagHold( + _BaseTagHoldsRestTransport._BaseCreateTagHold, TagHoldsRestStub + ): def __hash__(self): - return hash("CreateTagHold") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagHoldsRestTransport.CreateTagHold") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -372,45 +367,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{parent=tagValues/*}/tagHolds", - "body": "tag_hold", - }, - ] + http_options = ( + _BaseTagHoldsRestTransport._BaseCreateTagHold._get_http_options() + ) request, metadata = self._interceptor.pre_create_tag_hold(request, metadata) - pb_request = tag_holds.CreateTagHoldRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagHoldsRestTransport._BaseCreateTagHold._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagHoldsRestTransport._BaseCreateTagHold._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagHoldsRestTransport._BaseCreateTagHold._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagHoldsRestTransport._CreateTagHold._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -424,19 +410,33 @@ def __call__( resp = self._interceptor.post_create_tag_hold(resp) return resp - class _DeleteTagHold(TagHoldsRestStub): + class _DeleteTagHold( + _BaseTagHoldsRestTransport._BaseDeleteTagHold, TagHoldsRestStub + ): def __hash__(self): - return hash("DeleteTagHold") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagHoldsRestTransport.DeleteTagHold") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -466,38 +466,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=tagValues/*/tagHolds/*}", - }, - ] + http_options = ( + _BaseTagHoldsRestTransport._BaseDeleteTagHold._get_http_options() + ) request, metadata = self._interceptor.pre_delete_tag_hold(request, metadata) - pb_request = tag_holds.DeleteTagHoldRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagHoldsRestTransport._BaseDeleteTagHold._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagHoldsRestTransport._BaseDeleteTagHold._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagHoldsRestTransport._DeleteTagHold._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -511,19 +504,31 @@ def __call__( resp = self._interceptor.post_delete_tag_hold(resp) return resp - class _ListTagHolds(TagHoldsRestStub): + class _ListTagHolds(_BaseTagHoldsRestTransport._BaseListTagHolds, TagHoldsRestStub): def __hash__(self): - return hash("ListTagHolds") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagHoldsRestTransport.ListTagHolds") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -550,38 +555,31 @@ def __call__( The ListTagHolds response. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{parent=tagValues/*}/tagHolds", - }, - ] + http_options = ( + _BaseTagHoldsRestTransport._BaseListTagHolds._get_http_options() + ) request, metadata = self._interceptor.pre_list_tag_holds(request, metadata) - pb_request = tag_holds.ListTagHoldsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagHoldsRestTransport._BaseListTagHolds._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagHoldsRestTransport._BaseListTagHolds._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagHoldsRestTransport._ListTagHolds._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -625,7 +623,32 @@ def list_tag_holds( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(TagHoldsRestStub): + class _GetOperation(_BaseTagHoldsRestTransport._BaseGetOperation, TagHoldsRestStub): + def __hash__(self): + return hash("TagHoldsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -649,32 +672,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseTagHoldsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagHoldsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTagHoldsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TagHoldsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -682,8 +704,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest_base.py new file mode 100644 index 000000000000..cc0ab4a98734 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_holds/transports/rest_base.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import tag_holds + +from .base import DEFAULT_CLIENT_INFO, TagHoldsTransport + + +class _BaseTagHoldsRestTransport(TagHoldsTransport): + """Base REST backend transport for TagHolds. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateTagHold: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{parent=tagValues/*}/tagHolds", + "body": "tag_hold", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_holds.CreateTagHoldRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagHoldsRestTransport._BaseCreateTagHold._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTagHold: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=tagValues/*/tagHolds/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_holds.DeleteTagHoldRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagHoldsRestTransport._BaseDeleteTagHold._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTagHolds: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{parent=tagValues/*}/tagHolds", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_holds.ListTagHoldsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagHoldsRestTransport._BaseListTagHolds._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseTagHoldsRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py index 80c1781e4e09..1da8f0c88af8 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/async_client.py @@ -1398,11 +1398,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/client.py index 5d4ad39e6289..c27be9e6bfc2 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/client.py @@ -1815,11 +1815,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/README.rst new file mode 100644 index 000000000000..f2d762935614 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TagKeysTransport` is the ABC for all transports. +- public child `TagKeysGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TagKeysGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTagKeysRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TagKeysRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py index 9345339d6017..30df1367808f 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/base.py @@ -206,6 +206,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py index 9d0dd4200c82..86b19103dbb0 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -522,7 +526,7 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_tag_keys: gapic_v1.method_async.wrap_method( + self.list_tag_keys: self._wrap_method( self.list_tag_keys, default_retry=retries.AsyncRetry( initial=0.1, @@ -536,7 +540,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_tag_key: gapic_v1.method_async.wrap_method( + self.get_tag_key: self._wrap_method( self.get_tag_key, default_retry=retries.AsyncRetry( initial=0.1, @@ -550,27 +554,27 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_namespaced_tag_key: gapic_v1.method_async.wrap_method( + self.get_namespaced_tag_key: self._wrap_method( self.get_namespaced_tag_key, default_timeout=None, client_info=client_info, ), - self.create_tag_key: gapic_v1.method_async.wrap_method( + self.create_tag_key: self._wrap_method( self.create_tag_key, default_timeout=60.0, client_info=client_info, ), - self.update_tag_key: gapic_v1.method_async.wrap_method( + self.update_tag_key: self._wrap_method( self.update_tag_key, default_timeout=60.0, client_info=client_info, ), - self.delete_tag_key: gapic_v1.method_async.wrap_method( + self.delete_tag_key: self._wrap_method( self.delete_tag_key, default_timeout=60.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_retry=retries.AsyncRetry( initial=0.1, @@ -584,21 +588,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=60.0, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py index e137b70ccc5d..5ead368963ee 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import tag_keys + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTagKeysRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_keys - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import TagKeysTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -371,8 +361,8 @@ class TagKeysRestStub: _interceptor: TagKeysRestInterceptor -class TagKeysRestTransport(TagKeysTransport): - """REST backend transport for TagKeys. +class TagKeysRestTransport(_BaseTagKeysRestTransport): + """REST backend synchronous transport for TagKeys. Allow users to create and manage tag keys. @@ -381,7 +371,6 @@ class TagKeysRestTransport(TagKeysTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -435,21 +424,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -495,19 +475,32 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateTagKey(TagKeysRestStub): + class _CreateTagKey(_BaseTagKeysRestTransport._BaseCreateTagKey, TagKeysRestStub): def __hash__(self): - return hash("CreateTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.CreateTagKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -537,45 +530,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/tagKeys", - "body": "tag_key", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseCreateTagKey._get_http_options() + ) request, metadata = self._interceptor.pre_create_tag_key(request, metadata) - pb_request = tag_keys.CreateTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagKeysRestTransport._BaseCreateTagKey._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagKeysRestTransport._BaseCreateTagKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseCreateTagKey._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagKeysRestTransport._CreateTagKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -589,19 +573,31 @@ def __call__( resp = self._interceptor.post_create_tag_key(resp) return resp - class _DeleteTagKey(TagKeysRestStub): + class _DeleteTagKey(_BaseTagKeysRestTransport._BaseDeleteTagKey, TagKeysRestStub): def __hash__(self): - return hash("DeleteTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.DeleteTagKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -631,38 +627,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=tagKeys/*}", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseDeleteTagKey._get_http_options() + ) request, metadata = self._interceptor.pre_delete_tag_key(request, metadata) - pb_request = tag_keys.DeleteTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagKeysRestTransport._BaseDeleteTagKey._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseDeleteTagKey._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagKeysRestTransport._DeleteTagKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -676,19 +665,32 @@ def __call__( resp = self._interceptor.post_delete_tag_key(resp) return resp - class _GetIamPolicy(TagKeysRestStub): + class _GetIamPolicy(_BaseTagKeysRestTransport._BaseGetIamPolicy, TagKeysRestStub): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -789,45 +791,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagKeys/*}:getIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagKeysRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagKeysRestTransport._BaseGetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagKeysRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -843,21 +836,33 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetNamespacedTagKey(TagKeysRestStub): + class _GetNamespacedTagKey( + _BaseTagKeysRestTransport._BaseGetNamespacedTagKey, TagKeysRestStub + ): def __hash__(self): - return hash("GetNamespacedTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "name": "", - } - - @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 - } + return hash("TagKeysRestTransport.GetNamespacedTagKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -886,40 +891,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/tagKeys/namespaced", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseGetNamespacedTagKey._get_http_options() + ) request, metadata = self._interceptor.pre_get_namespaced_tag_key( request, metadata ) - pb_request = tag_keys.GetNamespacedTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseTagKeysRestTransport._BaseGetNamespacedTagKey._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagKeysRestTransport._BaseGetNamespacedTagKey._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagKeysRestTransport._GetNamespacedTagKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -935,19 +929,31 @@ def __call__( resp = self._interceptor.post_get_namespaced_tag_key(resp) return resp - class _GetTagKey(TagKeysRestStub): + class _GetTagKey(_BaseTagKeysRestTransport._BaseGetTagKey, TagKeysRestStub): def __hash__(self): - return hash("GetTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.GetTagKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -976,38 +982,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=tagKeys/*}", - }, - ] + http_options = _BaseTagKeysRestTransport._BaseGetTagKey._get_http_options() request, metadata = self._interceptor.pre_get_tag_key(request, metadata) - pb_request = tag_keys.GetTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagKeysRestTransport._BaseGetTagKey._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseGetTagKey._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagKeysRestTransport._GetTagKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1023,21 +1020,31 @@ def __call__( resp = self._interceptor.post_get_tag_key(resp) return resp - class _ListTagKeys(TagKeysRestStub): + class _ListTagKeys(_BaseTagKeysRestTransport._BaseListTagKeys, TagKeysRestStub): def __hash__(self): - return hash("ListTagKeys") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("TagKeysRestTransport.ListTagKeys") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1064,38 +1071,31 @@ def __call__( The ListTagKeys response message. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/tagKeys", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseListTagKeys._get_http_options() + ) request, metadata = self._interceptor.pre_list_tag_keys(request, metadata) - pb_request = tag_keys.ListTagKeysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagKeysRestTransport._BaseListTagKeys._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseListTagKeys._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagKeysRestTransport._ListTagKeys._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1111,19 +1111,32 @@ def __call__( resp = self._interceptor.post_list_tag_keys(resp) return resp - class _SetIamPolicy(TagKeysRestStub): + class _SetIamPolicy(_BaseTagKeysRestTransport._BaseSetIamPolicy, TagKeysRestStub): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1224,45 +1237,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagKeys/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagKeysRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagKeysRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagKeysRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1278,19 +1282,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(TagKeysRestStub): + class _TestIamPermissions( + _BaseTagKeysRestTransport._BaseTestIamPermissions, TagKeysRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1316,47 +1335,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagKeys/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseTagKeysRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagKeysRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagKeysRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagKeysRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1372,19 +1378,32 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UpdateTagKey(TagKeysRestStub): + class _UpdateTagKey(_BaseTagKeysRestTransport._BaseUpdateTagKey, TagKeysRestStub): def __hash__(self): - return hash("UpdateTagKey") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagKeysRestTransport.UpdateTagKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1414,45 +1433,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v3/{tag_key.name=tagKeys/*}", - "body": "tag_key", - }, - ] + http_options = ( + _BaseTagKeysRestTransport._BaseUpdateTagKey._get_http_options() + ) request, metadata = self._interceptor.pre_update_tag_key(request, metadata) - pb_request = tag_keys.UpdateTagKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagKeysRestTransport._BaseUpdateTagKey._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagKeysRestTransport._BaseUpdateTagKey._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagKeysRestTransport._BaseUpdateTagKey._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagKeysRestTransport._UpdateTagKey._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1543,7 +1553,32 @@ def update_tag_key( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(TagKeysRestStub): + class _GetOperation(_BaseTagKeysRestTransport._BaseGetOperation, TagKeysRestStub): + def __hash__(self): + return hash("TagKeysRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1567,32 +1602,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseTagKeysRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagKeysRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTagKeysRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TagKeysRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1600,8 +1634,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest_base.py new file mode 100644 index 000000000000..9b537f24a164 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_keys/transports/rest_base.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import tag_keys + +from .base import DEFAULT_CLIENT_INFO, TagKeysTransport + + +class _BaseTagKeysRestTransport(TagKeysTransport): + """Base REST backend transport for TagKeys. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateTagKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/tagKeys", + "body": "tag_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.CreateTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseCreateTagKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTagKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=tagKeys/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.DeleteTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseDeleteTagKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagKeys/*}:getIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNamespacedTagKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "name": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/tagKeys/namespaced", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.GetNamespacedTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseGetNamespacedTagKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTagKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=tagKeys/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.GetTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseGetTagKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTagKeys: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/tagKeys", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.ListTagKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseListTagKeys._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagKeys/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagKeys/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTagKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{tag_key.name=tagKeys/*}", + "body": "tag_key", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_keys.UpdateTagKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagKeysRestTransport._BaseUpdateTagKey._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseTagKeysRestTransport",) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/async_client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/async_client.py index 0c31d4c5426b..a281aee5c2a0 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/async_client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/async_client.py @@ -1407,11 +1407,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/client.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/client.py index ea695e212a4d..01bfc2d8ca70 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/client.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/client.py @@ -1822,11 +1822,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/README.rst b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/README.rst new file mode 100644 index 000000000000..07ad6721a748 --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TagValuesTransport` is the ABC for all transports. +- public child `TagValuesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TagValuesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTagValuesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TagValuesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py index ae84e6ceea0b..a18dc8ab1a7e 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/base.py @@ -206,6 +206,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py index 4119021b8a7b..77154bab434a 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -230,6 +231,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -531,7 +535,7 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_tag_values: gapic_v1.method_async.wrap_method( + self.list_tag_values: self._wrap_method( self.list_tag_values, default_retry=retries.AsyncRetry( initial=0.1, @@ -545,7 +549,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_tag_value: gapic_v1.method_async.wrap_method( + self.get_tag_value: self._wrap_method( self.get_tag_value, default_retry=retries.AsyncRetry( initial=0.1, @@ -559,27 +563,27 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_namespaced_tag_value: gapic_v1.method_async.wrap_method( + self.get_namespaced_tag_value: self._wrap_method( self.get_namespaced_tag_value, default_timeout=None, client_info=client_info, ), - self.create_tag_value: gapic_v1.method_async.wrap_method( + self.create_tag_value: self._wrap_method( self.create_tag_value, default_timeout=60.0, client_info=client_info, ), - self.update_tag_value: gapic_v1.method_async.wrap_method( + self.update_tag_value: self._wrap_method( self.update_tag_value, default_timeout=60.0, client_info=client_info, ), - self.delete_tag_value: gapic_v1.method_async.wrap_method( + self.delete_tag_value: self._wrap_method( self.delete_tag_value, default_timeout=60.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_retry=retries.AsyncRetry( initial=0.1, @@ -593,21 +597,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=60.0, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py index 5550383e514a..a71b17acd032 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.resourcemanager_v3.types import tag_values + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTagValuesRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.resourcemanager_v3.types import tag_values - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import TagValuesTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -383,8 +373,8 @@ class TagValuesRestStub: _interceptor: TagValuesRestInterceptor -class TagValuesRestTransport(TagValuesTransport): - """REST backend transport for TagValues. +class TagValuesRestTransport(_BaseTagValuesRestTransport): + """REST backend synchronous transport for TagValues. Allow users to create and manage tag values. @@ -393,7 +383,6 @@ class TagValuesRestTransport(TagValuesTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -447,21 +436,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -507,19 +487,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateTagValue(TagValuesRestStub): + class _CreateTagValue( + _BaseTagValuesRestTransport._BaseCreateTagValue, TagValuesRestStub + ): def __hash__(self): - return hash("CreateTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.CreateTagValue") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -549,47 +544,40 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/tagValues", - "body": "tag_value", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseCreateTagValue._get_http_options() + ) request, metadata = self._interceptor.pre_create_tag_value( request, metadata ) - pb_request = tag_values.CreateTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagValuesRestTransport._BaseCreateTagValue._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseTagValuesRestTransport._BaseCreateTagValue._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseCreateTagValue._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagValuesRestTransport._CreateTagValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -603,19 +591,33 @@ def __call__( resp = self._interceptor.post_create_tag_value(resp) return resp - class _DeleteTagValue(TagValuesRestStub): + class _DeleteTagValue( + _BaseTagValuesRestTransport._BaseDeleteTagValue, TagValuesRestStub + ): def __hash__(self): - return hash("DeleteTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.DeleteTagValue") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -645,40 +647,33 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v3/{name=tagValues/*}", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseDeleteTagValue._get_http_options() + ) request, metadata = self._interceptor.pre_delete_tag_value( request, metadata ) - pb_request = tag_values.DeleteTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagValuesRestTransport._BaseDeleteTagValue._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseDeleteTagValue._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagValuesRestTransport._DeleteTagValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -692,19 +687,34 @@ def __call__( resp = self._interceptor.post_delete_tag_value(resp) return resp - class _GetIamPolicy(TagValuesRestStub): + class _GetIamPolicy( + _BaseTagValuesRestTransport._BaseGetIamPolicy, TagValuesRestStub + ): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -805,45 +815,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagValues/*}:getIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagValuesRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagValuesRestTransport._BaseGetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagValuesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -859,21 +860,33 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetNamespacedTagValue(TagValuesRestStub): + class _GetNamespacedTagValue( + _BaseTagValuesRestTransport._BaseGetNamespacedTagValue, TagValuesRestStub + ): def __hash__(self): - return hash("GetNamespacedTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "name": "", - } - - @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 - } + return hash("TagValuesRestTransport.GetNamespacedTagValue") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -904,40 +917,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/tagValues/namespaced", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseGetNamespacedTagValue._get_http_options() + ) request, metadata = self._interceptor.pre_get_namespaced_tag_value( request, metadata ) - pb_request = tag_values.GetNamespacedTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseTagValuesRestTransport._BaseGetNamespacedTagValue._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagValuesRestTransport._BaseGetNamespacedTagValue._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagValuesRestTransport._GetNamespacedTagValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -953,19 +955,31 @@ def __call__( resp = self._interceptor.post_get_namespaced_tag_value(resp) return resp - class _GetTagValue(TagValuesRestStub): + class _GetTagValue(_BaseTagValuesRestTransport._BaseGetTagValue, TagValuesRestStub): def __hash__(self): - return hash("GetTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.GetTagValue") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -996,38 +1010,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=tagValues/*}", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseGetTagValue._get_http_options() + ) request, metadata = self._interceptor.pre_get_tag_value(request, metadata) - pb_request = tag_values.GetTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagValuesRestTransport._BaseGetTagValue._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseGetTagValue._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagValuesRestTransport._GetTagValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1043,21 +1050,33 @@ def __call__( resp = self._interceptor.post_get_tag_value(resp) return resp - class _ListTagValues(TagValuesRestStub): + class _ListTagValues( + _BaseTagValuesRestTransport._BaseListTagValues, TagValuesRestStub + ): def __hash__(self): - return hash("ListTagValues") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "parent": "", - } - - @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 - } + return hash("TagValuesRestTransport.ListTagValues") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1086,38 +1105,31 @@ def __call__( The ListTagValues response. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/tagValues", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseListTagValues._get_http_options() + ) request, metadata = self._interceptor.pre_list_tag_values(request, metadata) - pb_request = tag_values.ListTagValuesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagValuesRestTransport._BaseListTagValues._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseListTagValues._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TagValuesRestTransport._ListTagValues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1133,19 +1145,34 @@ def __call__( resp = self._interceptor.post_list_tag_values(resp) return resp - class _SetIamPolicy(TagValuesRestStub): + class _SetIamPolicy( + _BaseTagValuesRestTransport._BaseSetIamPolicy, TagValuesRestStub + ): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1246,45 +1273,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagValues/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagValuesRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagValuesRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagValuesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1300,19 +1318,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(TagValuesRestStub): + class _TestIamPermissions( + _BaseTagValuesRestTransport._BaseTestIamPermissions, TagValuesRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1338,47 +1371,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v3/{resource=tagValues/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseTagValuesRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseTagValuesRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseTagValuesRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagValuesRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1394,19 +1414,34 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UpdateTagValue(TagValuesRestStub): + class _UpdateTagValue( + _BaseTagValuesRestTransport._BaseUpdateTagValue, TagValuesRestStub + ): def __hash__(self): - return hash("UpdateTagValue") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TagValuesRestTransport.UpdateTagValue") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1436,47 +1471,40 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v3/{tag_value.name=tagValues/*}", - "body": "tag_value", - }, - ] + http_options = ( + _BaseTagValuesRestTransport._BaseUpdateTagValue._get_http_options() + ) request, metadata = self._interceptor.pre_update_tag_value( request, metadata ) - pb_request = tag_values.UpdateTagValueRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseTagValuesRestTransport._BaseUpdateTagValue._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseTagValuesRestTransport._BaseUpdateTagValue._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTagValuesRestTransport._BaseUpdateTagValue._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = TagValuesRestTransport._UpdateTagValue._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1569,7 +1597,34 @@ def update_tag_value( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(TagValuesRestStub): + class _GetOperation( + _BaseTagValuesRestTransport._BaseGetOperation, TagValuesRestStub + ): + def __hash__(self): + return hash("TagValuesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1593,32 +1648,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v3/{name=operations/**}", - }, - ] - + http_options = ( + _BaseTagValuesRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTagValuesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTagValuesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TagValuesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1626,8 +1680,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest_base.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest_base.py new file mode 100644 index 000000000000..8f6a3990a26c --- /dev/null +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/tag_values/transports/rest_base.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.resourcemanager_v3.types import tag_values + +from .base import DEFAULT_CLIENT_INFO, TagValuesTransport + + +class _BaseTagValuesRestTransport(TagValuesTransport): + """Base REST backend transport for TagValues. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "cloudresourcemanager.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudresourcemanager.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateTagValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/tagValues", + "body": "tag_value", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.CreateTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseCreateTagValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTagValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v3/{name=tagValues/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.DeleteTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseDeleteTagValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagValues/*}:getIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNamespacedTagValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "name": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/tagValues/namespaced", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.GetNamespacedTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseGetNamespacedTagValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTagValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=tagValues/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.GetTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseGetTagValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTagValues: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "parent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/tagValues", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.ListTagValuesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseListTagValues._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagValues/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v3/{resource=tagValues/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTagValue: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v3/{tag_value.name=tagValues/*}", + "body": "tag_value", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tag_values.UpdateTagValueRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTagValuesRestTransport._BaseUpdateTagValue._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v3/{name=operations/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseTagValuesRestTransport",) diff --git a/packages/google-cloud-resource-manager/setup.py b/packages/google-cloud-resource-manager/setup.py index 22ec7725e2b0..5533f1f277ce 100644 --- a/packages/google-cloud-resource-manager/setup.py +++ b/packages/google-cloud-resource-manager/setup.py @@ -49,6 +49,7 @@ "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -91,6 +92,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_folders.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_folders.py index 5b1f7b326ad9..acab2dff367a 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_folders.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_folders.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,16 +65,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import expr_pb2 # type: ignore -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.resourcemanager_v3.services.folders import ( FoldersAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.resourcemanager_v3.types import folders +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1113,25 +1136,6 @@ def test_get_folder(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.GetFolderRequest() - - def test_get_folder_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1195,40 +1199,13 @@ def test_get_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - folders.Folder( - name="name_value", - parent="parent_value", - display_name="display_name_value", - state=folders.Folder.State.ACTIVE, - etag="etag_value", - ) - ) - response = await client.get_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.GetFolderRequest() - - @pytest.mark.asyncio async def test_get_folder_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1267,7 +1244,7 @@ async def test_get_folder_async( transport: str = "grpc_asyncio", request_type=folders.GetFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1341,7 +1318,7 @@ def test_get_folder_field_headers(): @pytest.mark.asyncio async def test_get_folder_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1409,7 +1386,7 @@ def test_get_folder_flattened_error(): @pytest.mark.asyncio async def test_get_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1436,7 +1413,7 @@ async def test_get_folder_flattened_async(): @pytest.mark.asyncio async def test_get_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1484,25 +1461,6 @@ def test_list_folders(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_folders_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.ListFoldersRequest() - - def test_list_folders_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1568,29 +1526,6 @@ def test_list_folders_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_folders_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - folders.ListFoldersResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.ListFoldersRequest() - - @pytest.mark.asyncio async def test_list_folders_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1599,7 +1534,7 @@ async def test_list_folders_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1638,7 +1573,7 @@ async def test_list_folders_async( transport: str = "grpc_asyncio", request_type=folders.ListFoldersRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1713,7 +1648,7 @@ def test_list_folders_flattened_error(): @pytest.mark.asyncio async def test_list_folders_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1742,7 +1677,7 @@ async def test_list_folders_flattened_async(): @pytest.mark.asyncio async def test_list_folders_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1849,7 +1784,7 @@ def test_list_folders_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_folders_async_pager(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1899,7 +1834,7 @@ async def test_list_folders_async_pager(): @pytest.mark.asyncio async def test_list_folders_async_pages(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1981,25 +1916,6 @@ def test_search_folders(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_folders_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_folders), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.SearchFoldersRequest() - - def test_search_folders_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2065,29 +1981,6 @@ def test_search_folders_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_folders_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_folders), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - folders.SearchFoldersResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_folders() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.SearchFoldersRequest() - - @pytest.mark.asyncio async def test_search_folders_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2096,7 +1989,7 @@ async def test_search_folders_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2135,7 +2028,7 @@ async def test_search_folders_async( transport: str = "grpc_asyncio", request_type=folders.SearchFoldersRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2210,7 +2103,7 @@ def test_search_folders_flattened_error(): @pytest.mark.asyncio async def test_search_folders_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2239,7 +2132,7 @@ async def test_search_folders_flattened_async(): @pytest.mark.asyncio async def test_search_folders_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2346,7 +2239,7 @@ def test_search_folders_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_folders_async_pager(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2396,7 +2289,7 @@ async def test_search_folders_async_pager(): @pytest.mark.asyncio async def test_search_folders_async_pages(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2475,25 +2368,6 @@ def test_create_folder(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.CreateFolderRequest() - - def test_create_folder_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2558,27 +2432,6 @@ def test_create_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.CreateFolderRequest() - - @pytest.mark.asyncio async def test_create_folder_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2587,7 +2440,7 @@ async def test_create_folder_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2631,7 +2484,7 @@ async def test_create_folder_async( transport: str = "grpc_asyncio", request_type=folders.CreateFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2703,7 +2556,7 @@ def test_create_folder_flattened_error(): @pytest.mark.asyncio async def test_create_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2732,7 +2585,7 @@ async def test_create_folder_flattened_async(): @pytest.mark.asyncio async def test_create_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2777,25 +2630,6 @@ def test_update_folder(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UpdateFolderRequest() - - def test_update_folder_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2860,27 +2694,6 @@ def test_update_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UpdateFolderRequest() - - @pytest.mark.asyncio async def test_update_folder_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2889,7 +2702,7 @@ async def test_update_folder_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2933,7 +2746,7 @@ async def test_update_folder_async( transport: str = "grpc_asyncio", request_type=folders.UpdateFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2996,7 +2809,7 @@ def test_update_folder_field_headers(): @pytest.mark.asyncio async def test_update_folder_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3071,7 +2884,7 @@ def test_update_folder_flattened_error(): @pytest.mark.asyncio async def test_update_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3104,7 +2917,7 @@ async def test_update_folder_flattened_async(): @pytest.mark.asyncio async def test_update_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3150,25 +2963,6 @@ def test_move_folder(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_move_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.move_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.move_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.MoveFolderRequest() - - def test_move_folder_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3239,27 +3033,6 @@ def test_move_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_move_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.move_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.move_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.MoveFolderRequest() - - @pytest.mark.asyncio async def test_move_folder_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3268,7 +3041,7 @@ async def test_move_folder_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3312,7 +3085,7 @@ async def test_move_folder_async( transport: str = "grpc_asyncio", request_type=folders.MoveFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3375,7 +3148,7 @@ def test_move_folder_field_headers(): @pytest.mark.asyncio async def test_move_folder_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3450,7 +3223,7 @@ def test_move_folder_flattened_error(): @pytest.mark.asyncio async def test_move_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3483,7 +3256,7 @@ async def test_move_folder_flattened_async(): @pytest.mark.asyncio async def test_move_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3529,28 +3302,9 @@ def test_delete_folder(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.DeleteFolderRequest() - - -def test_delete_folder_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_delete_folder_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -3616,27 +3370,6 @@ def test_delete_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.DeleteFolderRequest() - - @pytest.mark.asyncio async def test_delete_folder_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3645,7 +3378,7 @@ async def test_delete_folder_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3689,7 +3422,7 @@ async def test_delete_folder_async( transport: str = "grpc_asyncio", request_type=folders.DeleteFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3752,7 +3485,7 @@ def test_delete_folder_field_headers(): @pytest.mark.asyncio async def test_delete_folder_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3822,7 +3555,7 @@ def test_delete_folder_flattened_error(): @pytest.mark.asyncio async def test_delete_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3851,7 +3584,7 @@ async def test_delete_folder_flattened_async(): @pytest.mark.asyncio async def test_delete_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3896,25 +3629,6 @@ def test_undelete_folder(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_undelete_folder_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.undelete_folder), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.undelete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UndeleteFolderRequest() - - def test_undelete_folder_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3983,27 +3697,6 @@ def test_undelete_folder_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_undelete_folder_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.undelete_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.undelete_folder() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == folders.UndeleteFolderRequest() - - @pytest.mark.asyncio async def test_undelete_folder_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4012,7 +3705,7 @@ async def test_undelete_folder_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4056,7 +3749,7 @@ async def test_undelete_folder_async( transport: str = "grpc_asyncio", request_type=folders.UndeleteFolderRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4119,7 +3812,7 @@ def test_undelete_folder_field_headers(): @pytest.mark.asyncio async def test_undelete_folder_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4189,7 +3882,7 @@ def test_undelete_folder_flattened_error(): @pytest.mark.asyncio async def test_undelete_folder_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4218,7 +3911,7 @@ async def test_undelete_folder_flattened_async(): @pytest.mark.asyncio async def test_undelete_folder_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4268,25 +3961,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4350,30 +4024,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4382,7 +4032,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4421,7 +4071,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4489,7 +4139,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4574,7 +4224,7 @@ def test_get_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4601,7 +4251,7 @@ async def test_get_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4651,25 +4301,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4733,30 +4364,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4765,7 +4372,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4804,7 +4411,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4872,7 +4479,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4958,7 +4565,7 @@ def test_set_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4985,7 +4592,7 @@ async def test_set_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5035,27 +4642,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5125,31 +4711,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5158,7 +4719,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5198,7 +4759,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5268,7 +4829,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5366,7 +4927,7 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5401,7 +4962,7 @@ async def test_test_iam_permissions_flattened_async(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5414,54 +4975,6 @@ async def test_test_iam_permissions_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - folders.GetFolderRequest, - dict, - ], -) -def test_get_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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 = folders.Folder( - name="name_value", - parent="parent_value", - display_name="display_name_value", - state=folders.Folder.State.ACTIVE, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = folders.Folder.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_folder(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, folders.Folder) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.state == folders.Folder.State.ACTIVE - assert response.etag == "etag_value" - - def test_get_folder_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5579,85 +5092,10 @@ def test_get_folder_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( +def test_get_folder_rest_flattened(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_get_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_get_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.GetFolderRequest.pb(folders.GetFolderRequest()) - 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 = folders.Folder.to_json(folders.Folder()) - - request = folders.GetFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.Folder() - - client.get_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_folder_rest_bad_request( - transport: str = "rest", request_type=folders.GetFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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_folder(request) - - -def test_get_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5709,52 +5147,6 @@ def test_get_folder_rest_flattened_error(transport: str = "rest"): ) -def test_get_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - folders.ListFoldersRequest, - dict, - ], -) -def test_list_folders_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = folders.ListFoldersResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = folders.ListFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_folders(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFoldersPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_folders_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5900,83 +5292,6 @@ def test_list_folders_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_folders_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_list_folders" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_list_folders" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.ListFoldersRequest.pb(folders.ListFoldersRequest()) - 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 = folders.ListFoldersResponse.to_json( - folders.ListFoldersResponse() - ) - - request = folders.ListFoldersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.ListFoldersResponse() - - client.list_folders( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_folders_rest_bad_request( - transport: str = "rest", request_type=folders.ListFoldersRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_folders(request) - - def test_list_folders_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6091,46 +5406,6 @@ def test_list_folders_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - folders.SearchFoldersRequest, - dict, - ], -) -def test_search_folders_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = folders.SearchFoldersResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = folders.SearchFoldersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_folders(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchFoldersPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_folders_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6167,96 +5442,19 @@ def test_search_folders_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_folders_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( +def test_search_folders_rest_flattened(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + transport="rest", ) - client = FoldersClient(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.FoldersRestInterceptor, "post_search_folders" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_search_folders" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.SearchFoldersRequest.pb(folders.SearchFoldersRequest()) - 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 = folders.SearchFoldersResponse.to_json( - folders.SearchFoldersResponse() - ) + # 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 = folders.SearchFoldersResponse() - request = folders.SearchFoldersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = folders.SearchFoldersResponse() - - client.search_folders( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_folders_rest_bad_request( - transport: str = "rest", request_type=folders.SearchFoldersRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.search_folders(request) - - -def test_search_folders_rest_flattened(): - client = FoldersClient( - 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 = folders.SearchFoldersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} + # get arguments that satisfy an http rule for this method + sample_request = {} # get truthy value for each flattened field mock_args = dict( @@ -6360,118 +5558,6 @@ def test_search_folders_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - folders.CreateFolderRequest, - dict, - ], -) -def test_create_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["folder"] = { - "name": "name_value", - "parent": "parent_value", - "display_name": "display_name_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = folders.CreateFolderRequest.meta.fields["folder"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["folder"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["folder"][field])): - del request_init["folder"][field][i][subfield] - else: - del request_init["folder"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_folder_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6586,85 +5672,6 @@ def test_create_folder_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("folder",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.FoldersRestInterceptor, "post_create_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_create_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.CreateFolderRequest.pb(folders.CreateFolderRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = folders.CreateFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_folder_rest_bad_request( - transport: str = "rest", request_type=folders.CreateFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.create_folder(request) - - def test_create_folder_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6716,139 +5723,21 @@ def test_create_folder_rest_flattened_error(transport: str = "rest"): ) -def test_create_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_folder_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - folders.UpdateFolderRequest, - dict, - ], -) -def test_update_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"folder": {"name": "folders/sample1"}} - request_init["folder"] = { - "name": "folders/sample1", - "parent": "parent_value", - "display_name": "display_name_value", - "state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = folders.UpdateFolderRequest.meta.fields["folder"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["folder"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["folder"][field])): - del request_init["folder"][field][i][subfield] - else: - del request_init["folder"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_folder_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_folder in client._transport._wrapped_methods + # Ensure method has been cached + assert client._transport.update_folder in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -6958,85 +5847,6 @@ def test_update_folder_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.FoldersRestInterceptor, "post_update_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_update_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.UpdateFolderRequest.pb(folders.UpdateFolderRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = folders.UpdateFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_folder_rest_bad_request( - transport: str = "rest", request_type=folders.UpdateFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"folder": {"name": "folders/sample1"}} - 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_folder(request) - - def test_update_folder_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7092,47 +5902,6 @@ def test_update_folder_rest_flattened_error(transport: str = "rest"): ) -def test_update_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - folders.MoveFolderRequest, - dict, - ], -) -def test_move_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.move_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_move_folder_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7264,89 +6033,10 @@ def test_move_folder_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_move_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( +def test_move_folder_rest_flattened(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.FoldersRestInterceptor, "post_move_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_move_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.MoveFolderRequest.pb(folders.MoveFolderRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = folders.MoveFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.move_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_move_folder_rest_bad_request( - transport: str = "rest", request_type=folders.MoveFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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.move_folder(request) - - -def test_move_folder_rest_flattened(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7398,47 +6088,6 @@ def test_move_folder_rest_flattened_error(transport: str = "rest"): ) -def test_move_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - folders.DeleteFolderRequest, - dict, - ], -) -def test_delete_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_folder_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7557,85 +6206,6 @@ def test_delete_folder_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.FoldersRestInterceptor, "post_delete_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_delete_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.DeleteFolderRequest.pb(folders.DeleteFolderRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = folders.DeleteFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_folder_rest_bad_request( - transport: str = "rest", request_type=folders.DeleteFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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.delete_folder(request) - - def test_delete_folder_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7689,47 +6259,6 @@ def test_delete_folder_rest_flattened_error(transport: str = "rest"): ) -def test_delete_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - folders.UndeleteFolderRequest, - dict, - ], -) -def test_undelete_folder_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.undelete_folder(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_undelete_folder_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7851,104 +6380,25 @@ def test_undelete_folder_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_folder_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( +def test_undelete_folder_rest_flattened(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + transport="rest", ) - client = FoldersClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.FoldersRestInterceptor, "post_undelete_folder" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_undelete_folder" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = folders.UndeleteFolderRequest.pb(folders.UndeleteFolderRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = folders.UndeleteFolderRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "folders/sample1"} - client.undelete_folder( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_folder_rest_bad_request( - transport: str = "rest", request_type=folders.UndeleteFolderRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1"} - 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.undelete_folder(request) - - -def test_undelete_folder_rest_flattened(): - client = FoldersClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "folders/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7983,52 +6433,6 @@ def test_undelete_folder_rest_flattened_error(transport: str = "rest"): ) -def test_undelete_folder_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8147,81 +6551,6 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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_iam_policy(request) - - def test_get_iam_policy_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8275,52 +6604,6 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_get_iam_policy_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8447,100 +6730,25 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( +def test_set_iam_policy_rest_flattened(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + transport="rest", ) - client = FoldersClient(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.FoldersRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) + # 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 = policy_pb2.Policy() - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "folders/sample1"} - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = FoldersClient( - 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 = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {"resource": "folders/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - resource="resource_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -8575,50 +6783,6 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_set_iam_policy_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8753,83 +6917,6 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.FoldersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), - ) - client = FoldersClient(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.FoldersRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.FoldersRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "folders/sample1"} - 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.test_iam_permissions(request) - - def test_test_iam_permissions_rest_flattened(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8870,132 +6957,2371 @@ def test_test_iam_permissions_rest_flattened(): ) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = FoldersClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FoldersClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FoldersClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FoldersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FoldersClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FoldersGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FoldersGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FoldersGrpcTransport, + transports.FoldersGrpcAsyncIOTransport, + transports.FoldersRestTransport, + ], +) +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_transport_kind_grpc(): + transport = FoldersClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + call.return_value = folders.Folder() + client.get_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.GetFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_folders_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + call.return_value = folders.ListFoldersResponse() + client.list_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.ListFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_folders_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_folders), "__call__") as call: + call.return_value = folders.SearchFoldersResponse() + client.search_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.SearchFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.CreateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UpdateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.move_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.MoveFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.DeleteFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_folder_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.undelete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UndeleteFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = FoldersAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + folders.Folder( + name="name_value", + parent="parent_value", + display_name="display_name_value", + state=folders.Folder.State.ACTIVE, + etag="etag_value", + ) + ) + await client.get_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.GetFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_folders_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + folders.ListFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.ListFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_folders_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_folders), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + folders.SearchFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.SearchFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.CreateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UpdateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_move_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.move_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.MoveFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.DeleteFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_undelete_folder_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.undelete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UndeleteFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = FoldersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_folder_rest_bad_request(request_type=folders.GetFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.GetFolderRequest, + dict, + ], +) +def test_get_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = folders.Folder( + name="name_value", + parent="parent_value", + display_name="display_name_value", + state=folders.Folder.State.ACTIVE, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = folders.Folder.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_folder(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, folders.Folder) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.display_name == "display_name_value" + assert response.state == folders.Folder.State.ACTIVE + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_get_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_get_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.GetFolderRequest.pb(folders.GetFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = folders.Folder.to_json(folders.Folder()) + req.return_value.content = return_value + + request = folders.GetFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.Folder() + + client.get_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_folders_rest_bad_request(request_type=folders.ListFoldersRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_folders(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.ListFoldersRequest, + dict, + ], +) +def test_list_folders_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = folders.ListFoldersResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = folders.ListFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_folders(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFoldersPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_folders_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_list_folders" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_list_folders" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.ListFoldersRequest.pb(folders.ListFoldersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = folders.ListFoldersResponse.to_json( + folders.ListFoldersResponse() + ) + req.return_value.content = return_value + + request = folders.ListFoldersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.ListFoldersResponse() + + client.list_folders( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_folders_rest_bad_request(request_type=folders.SearchFoldersRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_folders(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.SearchFoldersRequest, + dict, + ], +) +def test_search_folders_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = folders.SearchFoldersResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = folders.SearchFoldersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_folders(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchFoldersPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_folders_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_search_folders" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_search_folders" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.SearchFoldersRequest.pb(folders.SearchFoldersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = folders.SearchFoldersResponse.to_json( + folders.SearchFoldersResponse() + ) + req.return_value.content = return_value + + request = folders.SearchFoldersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = folders.SearchFoldersResponse() + + client.search_folders( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_folder_rest_bad_request(request_type=folders.CreateFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.CreateFolderRequest, + dict, + ], +) +def test_create_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["folder"] = { + "name": "name_value", + "parent": "parent_value", + "display_name": "display_name_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = folders.CreateFolderRequest.meta.fields["folder"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["folder"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["folder"][field])): + del request_init["folder"][field][i][subfield] + else: + del request_init["folder"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_folder(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FoldersRestInterceptor, "post_create_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_create_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.CreateFolderRequest.pb(folders.CreateFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = folders.CreateFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_folder_rest_bad_request(request_type=folders.UpdateFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"folder": {"name": "folders/sample1"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.UpdateFolderRequest, + dict, + ], +) +def test_update_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"folder": {"name": "folders/sample1"}} + request_init["folder"] = { + "name": "folders/sample1", + "parent": "parent_value", + "display_name": "display_name_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = folders.UpdateFolderRequest.meta.fields["folder"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["folder"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["folder"][field])): + del request_init["folder"][field][i][subfield] + else: + del request_init["folder"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_folder(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FoldersRestInterceptor, "post_update_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_update_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.UpdateFolderRequest.pb(folders.UpdateFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = folders.UpdateFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_folder_rest_bad_request(request_type=folders.MoveFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.move_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.MoveFolderRequest, + dict, + ], +) +def test_move_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.move_folder(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FoldersRestInterceptor, "post_move_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_move_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.MoveFolderRequest.pb(folders.MoveFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = folders.MoveFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_folder_rest_bad_request(request_type=folders.DeleteFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.DeleteFolderRequest, + dict, + ], +) +def test_delete_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_folder(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FoldersRestInterceptor, "post_delete_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_delete_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.DeleteFolderRequest.pb(folders.DeleteFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = folders.DeleteFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_folder_rest_bad_request(request_type=folders.UndeleteFolderRequest): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.undelete_folder(request) + + +@pytest.mark.parametrize( + "request_type", + [ + folders.UndeleteFolderRequest, + dict, + ], +) +def test_undelete_folder_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.undelete_folder(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_folder_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.FoldersRestInterceptor, "post_undelete_folder" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_undelete_folder" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = folders.UndeleteFolderRequest.pb(folders.UndeleteFolderRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = folders.UndeleteFolderRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_folder( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "folders/sample1"} + 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.FoldersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.FoldersRestInterceptor(), + ) + client = FoldersClient(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.FoldersRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.FoldersRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_folder_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + client.get_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.GetFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_folders_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + client.list_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.ListFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_folders_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_folders), "__call__") as call: + client.search_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.SearchFoldersRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_folder_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + client.create_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.CreateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_folder_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_folder), "__call__") as call: + client.update_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UpdateFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_folder_empty_call_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_folder), "__call__") as call: + client.move_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.MoveFolderRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_folder_empty_call_rest(): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + client.delete_folder(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.DeleteFolderRequest() -def test_test_iam_permissions_rest_error(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FoldersGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_folder_empty_call_rest(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FoldersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_folder), "__call__") as call: + client.undelete_folder(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FoldersClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = folders.UndeleteFolderRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FoldersClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.FoldersGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = FoldersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FoldersGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FoldersClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FoldersGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.FoldersGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.FoldersGrpcTransport, - transports.FoldersGrpcAsyncIOTransport, - transports.FoldersRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = FoldersClient.get_transport_class(transport_name)( + +def test_folders_rest_lro_client(): + client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -9252,23 +9578,6 @@ def test_folders_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_folders_rest_lro_client(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -9665,76 +9974,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = FoldersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9762,7 +10001,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9817,7 +10056,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9864,7 +10103,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = FoldersAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -9880,22 +10119,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = FoldersClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = FoldersAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = FoldersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_organizations.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_organizations.py index a5914d84168d..396293347c13 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_organizations.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_organizations.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -39,16 +56,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import expr_pb2 # type: ignore -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.resourcemanager_v3.services.organizations import ( OrganizationsAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.resourcemanager_v3.types import organizations +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1166,25 +1189,6 @@ def test_get_organization(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_organization_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_organization), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_organization() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.GetOrganizationRequest() - - def test_get_organization_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1250,32 +1254,6 @@ def test_get_organization_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_organization_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_organization), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - organizations.Organization( - name="name_value", - display_name="display_name_value", - state=organizations.Organization.State.ACTIVE, - etag="etag_value", - ) - ) - response = await client.get_organization() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.GetOrganizationRequest() - - @pytest.mark.asyncio async def test_get_organization_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1284,7 +1262,7 @@ async def test_get_organization_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1323,7 +1301,7 @@ async def test_get_organization_async( transport: str = "grpc_asyncio", request_type=organizations.GetOrganizationRequest ): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1395,7 +1373,7 @@ def test_get_organization_field_headers(): @pytest.mark.asyncio async def test_get_organization_field_headers_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1465,7 +1443,7 @@ def test_get_organization_flattened_error(): @pytest.mark.asyncio async def test_get_organization_flattened_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1494,7 +1472,7 @@ async def test_get_organization_flattened_async(): @pytest.mark.asyncio async def test_get_organization_flattened_error_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1544,27 +1522,6 @@ def test_search_organizations(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_organizations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_organizations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.SearchOrganizationsRequest() - - def test_search_organizations_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1636,31 +1593,6 @@ def test_search_organizations_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_organizations_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_organizations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - organizations.SearchOrganizationsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_organizations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == organizations.SearchOrganizationsRequest() - - @pytest.mark.asyncio async def test_search_organizations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1669,7 +1601,7 @@ async def test_search_organizations_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1709,7 +1641,7 @@ async def test_search_organizations_async( request_type=organizations.SearchOrganizationsRequest, ): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1788,7 +1720,7 @@ def test_search_organizations_flattened_error(): @pytest.mark.asyncio async def test_search_organizations_flattened_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1819,7 +1751,7 @@ async def test_search_organizations_flattened_async(): @pytest.mark.asyncio async def test_search_organizations_flattened_error_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1930,7 +1862,7 @@ def test_search_organizations_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_organizations_async_pager(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1982,7 +1914,7 @@ async def test_search_organizations_async_pager(): @pytest.mark.asyncio async def test_search_organizations_async_pages(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2068,25 +2000,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2150,30 +2063,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2182,7 +2071,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2221,7 +2110,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2289,7 +2178,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2374,7 +2263,7 @@ def test_get_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2401,7 +2290,7 @@ async def test_get_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2451,25 +2340,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2533,30 +2403,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2565,7 +2411,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2604,7 +2450,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2672,7 +2518,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2758,7 +2604,7 @@ def test_set_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2785,7 +2631,7 @@ async def test_set_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2835,27 +2681,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2925,31 +2750,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2958,7 +2758,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2998,7 +2798,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3068,7 +2868,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3166,7 +2966,7 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3201,7 +3001,7 @@ async def test_test_iam_permissions_flattened_async(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3214,60 +3014,13 @@ async def test_test_iam_permissions_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - organizations.GetOrganizationRequest, - dict, - ], -) -def test_get_organization_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1"} - 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 = organizations.Organization( - name="name_value", - display_name="display_name_value", - state=organizations.Organization.State.ACTIVE, - etag="etag_value", - directory_customer_id="directory_customer_id_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organizations.Organization.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_organization(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, organizations.Organization) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.state == organizations.Organization.State.ACTIVE - assert response.etag == "etag_value" - - -def test_get_organization_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_get_organization_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -3382,87 +3135,6 @@ def test_get_organization_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_get_organization" - ) as post, mock.patch.object( - transports.OrganizationsRestInterceptor, "pre_get_organization" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = organizations.GetOrganizationRequest.pb( - organizations.GetOrganizationRequest() - ) - 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 = organizations.Organization.to_json( - organizations.Organization() - ) - - request = organizations.GetOrganizationRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organizations.Organization() - - client.get_organization( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_organization_rest_bad_request( - transport: str = "rest", request_type=organizations.GetOrganizationRequest -): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1"} - 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_organization(request) - - def test_get_organization_rest_flattened(): client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3518,52 +3190,6 @@ def test_get_organization_rest_flattened_error(transport: str = "rest"): ) -def test_get_organization_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - organizations.SearchOrganizationsRequest, - dict, - ], -) -def test_search_organizations_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = organizations.SearchOrganizationsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = organizations.SearchOrganizationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_organizations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchOrganizationsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_organizations_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3604,87 +3230,6 @@ def test_search_organizations_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_organizations_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_search_organizations" - ) as post, mock.patch.object( - transports.OrganizationsRestInterceptor, "pre_search_organizations" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = organizations.SearchOrganizationsRequest.pb( - organizations.SearchOrganizationsRequest() - ) - 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 = organizations.SearchOrganizationsResponse.to_json( - organizations.SearchOrganizationsResponse() - ) - - request = organizations.SearchOrganizationsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = organizations.SearchOrganizationsResponse() - - client.search_organizations( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_organizations_rest_bad_request( - transport: str = "rest", request_type=organizations.SearchOrganizationsRequest -): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.search_organizations(request) - - def test_search_organizations_rest_flattened(): client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3803,53 +3348,13 @@ def test_search_organizations_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "organizations/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -3961,83 +3466,6 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.OrganizationsRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "organizations/sample1"} - 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_iam_policy(request) - - def test_get_iam_policy_rest_flattened(): client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4092,52 +3520,6 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_get_iam_policy_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "organizations/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4264,83 +3646,6 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.OrganizationsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.OrganizationsRestInterceptor(), - ) - client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.OrganizationsRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "organizations/sample1"} - 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.set_iam_policy(request) - - def test_set_iam_policy_rest_flattened(): client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4395,50 +3700,6 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_set_iam_policy_rest_error(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "organizations/sample1"} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4573,8 +3834,754 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): +def test_test_iam_permissions_rest_flattened(): + client = OrganizationsClient( + 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 = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + permissions=["permissions_value"], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.test_iam_permissions(**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/v3/{resource=organizations/*}:testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = OrganizationsClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OrganizationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationsGrpcTransport, + transports.OrganizationsGrpcAsyncIOTransport, + transports.OrganizationsRestTransport, + ], +) +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_transport_kind_grpc(): + transport = OrganizationsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_organization_empty_call_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + call.return_value = organizations.Organization() + client.get_organization(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.GetOrganizationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_organizations_empty_call_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), "__call__" + ) as call: + call.return_value = organizations.SearchOrganizationsResponse() + client.search_organizations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.SearchOrganizationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OrganizationsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_organization_empty_call_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + organizations.Organization( + name="name_value", + display_name="display_name_value", + state=organizations.Organization.State.ACTIVE, + etag="etag_value", + ) + ) + await client.get_organization(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.GetOrganizationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_organizations_empty_call_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + organizations.SearchOrganizationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_organizations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.SearchOrganizationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OrganizationsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_organization_rest_bad_request( + request_type=organizations.GetOrganizationRequest, +): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_organization(request) + + +@pytest.mark.parametrize( + "request_type", + [ + organizations.GetOrganizationRequest, + dict, + ], +) +def test_get_organization_rest_call_success(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1"} + 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 = organizations.Organization( + name="name_value", + display_name="display_name_value", + state=organizations.Organization.State.ACTIVE, + etag="etag_value", + directory_customer_id="directory_customer_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organizations.Organization.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_organization(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, organizations.Organization) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.state == organizations.Organization.State.ACTIVE + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_organization_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_get_organization" + ) as post, mock.patch.object( + transports.OrganizationsRestInterceptor, "pre_get_organization" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = organizations.GetOrganizationRequest.pb( + organizations.GetOrganizationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = organizations.Organization.to_json(organizations.Organization()) + req.return_value.content = return_value + + request = organizations.GetOrganizationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organizations.Organization() + + client.get_organization( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_organizations_rest_bad_request( + request_type=organizations.SearchOrganizationsRequest, +): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_organizations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + organizations.SearchOrganizationsRequest, + dict, + ], +) +def test_search_organizations_rest_call_success(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = organizations.SearchOrganizationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = organizations.SearchOrganizationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_organizations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchOrganizationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_organizations_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_search_organizations" + ) as post, mock.patch.object( + transports.OrganizationsRestInterceptor, "pre_search_organizations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = organizations.SearchOrganizationsRequest.pb( + organizations.SearchOrganizationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = organizations.SearchOrganizationsResponse.to_json( + organizations.SearchOrganizationsResponse() + ) + req.return_value.content = return_value + + request = organizations.SearchOrganizationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = organizations.SearchOrganizationsResponse() + + client.search_organizations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.OrganizationsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4582,18 +4589,19 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): else transports.OrganizationsRestInterceptor(), ) client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_test_iam_permissions" + transports.OrganizationsRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( - transports.OrganizationsRestInterceptor, "pre_test_iam_permissions" + transports.OrganizationsRestInterceptor, "pre_get_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4601,22 +4609,20 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - request = iam_policy_pb2.TestIamPermissionsRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + post.return_value = policy_pb2.Policy() - client.test_iam_permissions( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -4628,14 +4634,128 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): post.assert_called_once() -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None + if null_interceptor + else transports.OrganizationsRestInterceptor(), ) + client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.OrganizationsRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) # send a request that will satisfy transcoding request_init = {"resource": "organizations/sample1"} request = request_type(**request_init) @@ -4645,180 +4765,274 @@ def test_test_iam_permissions_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.test_iam_permissions(request) -def test_test_iam_permissions_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1"} + 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 = iam_policy_pb2.TestIamPermissionsResponse() + return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) - # get arguments that satisfy an http rule for this method - sample_request = {"resource": "organizations/sample1"} + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) - # get truthy value for each flattened field - mock_args = dict( - resource="resource_value", - permissions=["permissions_value"], + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.OrganizationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationsRestInterceptor(), + ) + client = OrganizationsClient(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.OrganizationsRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.OrganizationsRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() ) - mock_args.update(sample_request) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.test_iam_permissions(**mock_args) + response = client.get_operation(request) - # 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/v3/{resource=organizations/*}:testIamPermissions" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_initialize_client_w_rest(): client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], - ) + assert client is not None -def test_test_iam_permissions_rest_error(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_organization_empty_call_rest(): client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_organization), "__call__") as call: + client.get_organization(request=None) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.GetOrganizationRequest() - # It is an error to provide a credentials file and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + assert args[0] == request_msg - # It is an error to provide an api_key and a transport instance. - transport = transports.OrganizationsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_organizations_empty_call_rest(): + client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_organizations), "__call__" + ) as call: + client.search_organizations(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OrganizationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = organizations.SearchOrganizationsRequest() + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OrganizationsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = OrganizationsClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OrganizationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() - transport = transports.OrganizationsGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.OrganizationsGrpcTransport, - transports.OrganizationsGrpcAsyncIOTransport, - transports.OrganizationsRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = OrganizationsClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -5417,76 +5631,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = OrganizationsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5514,7 +5658,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5569,7 +5713,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5616,7 +5760,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = OrganizationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5632,22 +5776,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = OrganizationsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = OrganizationsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = OrganizationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_projects.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_projects.py index 56e0807b186b..a9d35cd4a64f 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_projects.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_projects.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,16 +65,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import expr_pb2 # type: ignore -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.resourcemanager_v3.services.projects import ( ProjectsAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.resourcemanager_v3.types import projects +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1126,25 +1149,6 @@ def test_get_project(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.GetProjectRequest() - - def test_get_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1208,34 +1212,6 @@ def test_get_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - projects.Project( - name="name_value", - parent="parent_value", - project_id="project_id_value", - state=projects.Project.State.ACTIVE, - display_name="display_name_value", - etag="etag_value", - ) - ) - response = await client.get_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.GetProjectRequest() - - @pytest.mark.asyncio async def test_get_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1244,7 +1220,7 @@ async def test_get_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1283,7 +1259,7 @@ async def test_get_project_async( transport: str = "grpc_asyncio", request_type=projects.GetProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1359,7 +1335,7 @@ def test_get_project_field_headers(): @pytest.mark.asyncio async def test_get_project_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1427,7 +1403,7 @@ def test_get_project_flattened_error(): @pytest.mark.asyncio async def test_get_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1454,7 +1430,7 @@ async def test_get_project_flattened_async(): @pytest.mark.asyncio async def test_get_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1502,25 +1478,6 @@ def test_list_projects(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_projects_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_projects), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.ListProjectsRequest() - - def test_list_projects_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1586,29 +1543,6 @@ def test_list_projects_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_projects_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_projects), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - projects.ListProjectsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.ListProjectsRequest() - - @pytest.mark.asyncio async def test_list_projects_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1617,7 +1551,7 @@ async def test_list_projects_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1656,7 +1590,7 @@ async def test_list_projects_async( transport: str = "grpc_asyncio", request_type=projects.ListProjectsRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1731,7 +1665,7 @@ def test_list_projects_flattened_error(): @pytest.mark.asyncio async def test_list_projects_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1760,7 +1694,7 @@ async def test_list_projects_flattened_async(): @pytest.mark.asyncio async def test_list_projects_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1867,7 +1801,7 @@ def test_list_projects_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_projects_async_pager(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1917,7 +1851,7 @@ async def test_list_projects_async_pager(): @pytest.mark.asyncio async def test_list_projects_async_pages(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1999,25 +1933,6 @@ def test_search_projects(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_search_projects_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_projects), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.SearchProjectsRequest() - - def test_search_projects_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2083,29 +1998,6 @@ def test_search_projects_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_projects_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_projects), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - projects.SearchProjectsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.search_projects() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.SearchProjectsRequest() - - @pytest.mark.asyncio async def test_search_projects_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2114,7 +2006,7 @@ async def test_search_projects_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2153,7 +2045,7 @@ async def test_search_projects_async( transport: str = "grpc_asyncio", request_type=projects.SearchProjectsRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2228,7 +2120,7 @@ def test_search_projects_flattened_error(): @pytest.mark.asyncio async def test_search_projects_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2257,7 +2149,7 @@ async def test_search_projects_flattened_async(): @pytest.mark.asyncio async def test_search_projects_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2364,7 +2256,7 @@ def test_search_projects_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_projects_async_pager(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2414,7 +2306,7 @@ async def test_search_projects_async_pager(): @pytest.mark.asyncio async def test_search_projects_async_pages(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2493,25 +2385,6 @@ def test_create_project(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.CreateProjectRequest() - - def test_create_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2576,27 +2449,6 @@ def test_create_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.CreateProjectRequest() - - @pytest.mark.asyncio async def test_create_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2605,7 +2457,7 @@ async def test_create_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2649,7 +2501,7 @@ async def test_create_project_async( transport: str = "grpc_asyncio", request_type=projects.CreateProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2721,7 +2573,7 @@ def test_create_project_flattened_error(): @pytest.mark.asyncio async def test_create_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2750,7 +2602,7 @@ async def test_create_project_flattened_async(): @pytest.mark.asyncio async def test_create_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2795,25 +2647,6 @@ def test_update_project(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UpdateProjectRequest() - - def test_update_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2878,27 +2711,6 @@ def test_update_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UpdateProjectRequest() - - @pytest.mark.asyncio async def test_update_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2907,7 +2719,7 @@ async def test_update_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2951,7 +2763,7 @@ async def test_update_project_async( transport: str = "grpc_asyncio", request_type=projects.UpdateProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3014,7 +2826,7 @@ def test_update_project_field_headers(): @pytest.mark.asyncio async def test_update_project_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3089,7 +2901,7 @@ def test_update_project_flattened_error(): @pytest.mark.asyncio async def test_update_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3122,7 +2934,7 @@ async def test_update_project_flattened_async(): @pytest.mark.asyncio async def test_update_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3168,25 +2980,6 @@ def test_move_project(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_move_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.move_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.move_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.MoveProjectRequest() - - def test_move_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3257,27 +3050,6 @@ def test_move_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_move_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.move_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.move_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.MoveProjectRequest() - - @pytest.mark.asyncio async def test_move_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3286,7 +3058,7 @@ async def test_move_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3330,7 +3102,7 @@ async def test_move_project_async( transport: str = "grpc_asyncio", request_type=projects.MoveProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3393,7 +3165,7 @@ def test_move_project_field_headers(): @pytest.mark.asyncio async def test_move_project_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3468,7 +3240,7 @@ def test_move_project_flattened_error(): @pytest.mark.asyncio async def test_move_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3501,7 +3273,7 @@ async def test_move_project_flattened_async(): @pytest.mark.asyncio async def test_move_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3547,28 +3319,9 @@ def test_delete_project(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.DeleteProjectRequest() - - -def test_delete_project_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_delete_project_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -3634,27 +3387,6 @@ def test_delete_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.DeleteProjectRequest() - - @pytest.mark.asyncio async def test_delete_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3663,7 +3395,7 @@ async def test_delete_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3707,7 +3439,7 @@ async def test_delete_project_async( transport: str = "grpc_asyncio", request_type=projects.DeleteProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3770,7 +3502,7 @@ def test_delete_project_field_headers(): @pytest.mark.asyncio async def test_delete_project_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3840,7 +3572,7 @@ def test_delete_project_flattened_error(): @pytest.mark.asyncio async def test_delete_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3869,7 +3601,7 @@ async def test_delete_project_flattened_async(): @pytest.mark.asyncio async def test_delete_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3914,25 +3646,6 @@ def test_undelete_project(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_undelete_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.undelete_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.undelete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UndeleteProjectRequest() - - def test_undelete_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4003,27 +3716,6 @@ def test_undelete_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_undelete_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.undelete_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.undelete_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == projects.UndeleteProjectRequest() - - @pytest.mark.asyncio async def test_undelete_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4032,7 +3724,7 @@ async def test_undelete_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4076,7 +3768,7 @@ async def test_undelete_project_async( transport: str = "grpc_asyncio", request_type=projects.UndeleteProjectRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4139,7 +3831,7 @@ def test_undelete_project_field_headers(): @pytest.mark.asyncio async def test_undelete_project_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4209,7 +3901,7 @@ def test_undelete_project_flattened_error(): @pytest.mark.asyncio async def test_undelete_project_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4238,7 +3930,7 @@ async def test_undelete_project_flattened_async(): @pytest.mark.asyncio async def test_undelete_project_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4288,25 +3980,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4370,30 +4043,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4402,7 +4051,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4441,7 +4090,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4509,7 +4158,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4594,7 +4243,7 @@ def test_get_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4621,7 +4270,7 @@ async def test_get_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4671,25 +4320,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4753,30 +4383,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4785,7 +4391,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4824,7 +4430,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4892,7 +4498,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4978,7 +4584,7 @@ def test_set_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5005,7 +4611,7 @@ async def test_set_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5055,27 +4661,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5145,31 +4730,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5178,7 +4738,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5218,7 +4778,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5288,7 +4848,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5386,7 +4946,7 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5421,7 +4981,7 @@ async def test_test_iam_permissions_flattened_async(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5434,56 +4994,6 @@ async def test_test_iam_permissions_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - projects.GetProjectRequest, - dict, - ], -) -def test_get_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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 = projects.Project( - name="name_value", - parent="parent_value", - project_id="project_id_value", - state=projects.Project.State.ACTIVE, - display_name="display_name_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = projects.Project.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_project(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, projects.Project) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.project_id == "project_id_value" - assert response.state == projects.Project.State.ACTIVE - assert response.display_name == "display_name_value" - assert response.etag == "etag_value" - - def test_get_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5601,85 +5111,10 @@ def test_get_project_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( +def test_get_project_rest_flattened(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_get_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_get_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.GetProjectRequest.pb(projects.GetProjectRequest()) - 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 = projects.Project.to_json(projects.Project()) - - request = projects.GetProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.Project() - - client.get_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_project_rest_bad_request( - transport: str = "rest", request_type=projects.GetProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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_project(request) - - -def test_get_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5731,52 +5166,6 @@ def test_get_project_rest_flattened_error(transport: str = "rest"): ) -def test_get_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - projects.ListProjectsRequest, - dict, - ], -) -def test_list_projects_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = projects.ListProjectsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = projects.ListProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_projects(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProjectsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_projects_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5922,83 +5311,6 @@ def test_list_projects_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_projects_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_list_projects" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_list_projects" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.ListProjectsRequest.pb(projects.ListProjectsRequest()) - 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 = projects.ListProjectsResponse.to_json( - projects.ListProjectsResponse() - ) - - request = projects.ListProjectsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.ListProjectsResponse() - - client.list_projects( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_projects_rest_bad_request( - transport: str = "rest", request_type=projects.ListProjectsRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_projects(request) - - def test_list_projects_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6115,46 +5427,6 @@ def test_list_projects_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - projects.SearchProjectsRequest, - dict, - ], -) -def test_search_projects_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = projects.SearchProjectsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = projects.SearchProjectsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search_projects(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchProjectsPager) - assert response.next_page_token == "next_page_token_value" - - def test_search_projects_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6191,96 +5463,19 @@ def test_search_projects_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_projects_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( +def test_search_projects_rest_flattened(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + transport="rest", ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_search_projects" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_search_projects" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.SearchProjectsRequest.pb(projects.SearchProjectsRequest()) - 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 = projects.SearchProjectsResponse.to_json( - projects.SearchProjectsResponse() - ) + # 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 = projects.SearchProjectsResponse() - request = projects.SearchProjectsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = projects.SearchProjectsResponse() - - client.search_projects( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_projects_rest_bad_request( - transport: str = "rest", request_type=projects.SearchProjectsRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.search_projects(request) - - -def test_search_projects_rest_flattened(): - client = ProjectsClient( - 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 = projects.SearchProjectsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} + # get arguments that satisfy an http rule for this method + sample_request = {} # get truthy value for each flattened field mock_args = dict( @@ -6384,120 +5579,6 @@ def test_search_projects_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - projects.CreateProjectRequest, - dict, - ], -) -def test_create_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["project"] = { - "name": "name_value", - "parent": "parent_value", - "project_id": "project_id_value", - "state": 1, - "display_name": "display_name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "etag": "etag_value", - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = projects.CreateProjectRequest.meta.fields["project"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["project"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["project"][field])): - del request_init["project"][field][i][subfield] - else: - del request_init["project"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6614,85 +5695,6 @@ def test_create_project_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("project",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectsRestInterceptor, "post_create_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_create_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.CreateProjectRequest.pb(projects.CreateProjectRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = projects.CreateProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_project_rest_bad_request( - transport: str = "rest", request_type=projects.CreateProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.create_project(request) - - def test_create_project_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6746,138 +5748,18 @@ def test_create_project_rest_flattened_error(transport: str = "rest"): ) -def test_create_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_project_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - projects.UpdateProjectRequest, - dict, - ], -) -def test_update_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"project": {"name": "projects/sample1"}} - request_init["project"] = { - "name": "projects/sample1", - "parent": "parent_value", - "project_id": "project_id_value", - "state": 1, - "display_name": "display_name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "etag": "etag_value", - "labels": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = projects.UpdateProjectRequest.meta.fields["project"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["project"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["project"][field])): - del request_init["project"][field][i][subfield] - else: - del request_init["project"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_project_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.update_project in client._transport._wrapped_methods @@ -6984,85 +5866,6 @@ def test_update_project_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("project",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectsRestInterceptor, "post_update_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_update_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.UpdateProjectRequest.pb(projects.UpdateProjectRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = projects.UpdateProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_project_rest_bad_request( - transport: str = "rest", request_type=projects.UpdateProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"project": {"name": "projects/sample1"}} - 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_project(request) - - def test_update_project_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7118,47 +5921,6 @@ def test_update_project_rest_flattened_error(transport: str = "rest"): ) -def test_update_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - projects.MoveProjectRequest, - dict, - ], -) -def test_move_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.move_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_move_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7290,89 +6052,10 @@ def test_move_project_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_move_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( +def test_move_project_rest_flattened(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectsRestInterceptor, "post_move_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_move_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.MoveProjectRequest.pb(projects.MoveProjectRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = projects.MoveProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.move_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_move_project_rest_bad_request( - transport: str = "rest", request_type=projects.MoveProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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.move_project(request) - - -def test_move_project_rest_flattened(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7424,47 +6107,6 @@ def test_move_project_rest_flattened_error(transport: str = "rest"): ) -def test_move_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - projects.DeleteProjectRequest, - dict, - ], -) -def test_delete_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7585,85 +6227,6 @@ def test_delete_project_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectsRestInterceptor, "post_delete_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_delete_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.DeleteProjectRequest.pb(projects.DeleteProjectRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = projects.DeleteProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_project_rest_bad_request( - transport: str = "rest", request_type=projects.DeleteProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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.delete_project(request) - - def test_delete_project_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7717,47 +6280,6 @@ def test_delete_project_rest_flattened_error(transport: str = "rest"): ) -def test_delete_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - projects.UndeleteProjectRequest, - dict, - ], -) -def test_undelete_project_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.undelete_project(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_undelete_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7881,104 +6403,23 @@ def test_undelete_project_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_project_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( +def test_undelete_project_rest_flattened(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + transport="rest", ) - client = ProjectsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectsRestInterceptor, "post_undelete_project" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_undelete_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = projects.UndeleteProjectRequest.pb( - projects.UndeleteProjectRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = projects.UndeleteProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1"} - client.undelete_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_project_rest_bad_request( - transport: str = "rest", request_type=projects.UndeleteProjectRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1"} - 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.undelete_project(request) - - -def test_undelete_project_rest_flattened(): - client = ProjectsClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) mock_args.update(sample_request) @@ -8015,52 +6456,6 @@ def test_undelete_project_rest_flattened_error(transport: str = "rest"): ) -def test_undelete_project_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8179,81 +6574,6 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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_iam_policy(request) - - def test_get_iam_policy_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8307,52 +6627,6 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_get_iam_policy_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8479,100 +6753,25 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( +def test_set_iam_policy_rest_flattened(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + transport="rest", ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) + # 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 = policy_pb2.Policy() - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "projects/sample1"} - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = ProjectsClient( - 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 = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {"resource": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - resource="resource_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -8607,50 +6806,6 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_set_iam_policy_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8785,83 +6940,6 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.ProjectsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), - ) - client = ProjectsClient(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.ProjectsRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.ProjectsRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1"} - 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.test_iam_permissions(request) - - def test_test_iam_permissions_rest_flattened(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8902,132 +6980,2382 @@ def test_test_iam_permissions_rest_flattened(): ) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = ProjectsClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProjectsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectsGrpcTransport, + transports.ProjectsGrpcAsyncIOTransport, + transports.ProjectsRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProjectsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + call.return_value = projects.Project() + client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_projects_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_projects), "__call__") as call: + call.return_value = projects.ListProjectsResponse() + client.list_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.ListProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_projects_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_projects), "__call__") as call: + call.return_value = projects.SearchProjectsResponse() + client.search_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.SearchProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_project), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.CreateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_project), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UpdateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_project), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.move_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.MoveProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_project), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.DeleteProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_project_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_project), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.undelete_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UndeleteProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProjectsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + projects.Project( + name="name_value", + parent="parent_value", + project_id="project_id_value", + state=projects.Project.State.ACTIVE, + display_name="display_name_value", + etag="etag_value", + ) + ) + await client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_projects_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_projects), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + projects.ListProjectsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.ListProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_projects_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_projects), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + projects.SearchProjectsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.search_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.SearchProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.CreateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UpdateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_move_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.move_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.MoveProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.DeleteProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_undelete_project_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.undelete_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UndeleteProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProjectsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_project_rest_bad_request(request_type=projects.GetProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.GetProjectRequest, + dict, + ], +) +def test_get_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = projects.Project( + name="name_value", + parent="parent_value", + project_id="project_id_value", + state=projects.Project.State.ACTIVE, + display_name="display_name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = projects.Project.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_project(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, projects.Project) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.project_id == "project_id_value" + assert response.state == projects.Project.State.ACTIVE + assert response.display_name == "display_name_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_get_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_get_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.GetProjectRequest.pb(projects.GetProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = projects.Project.to_json(projects.Project()) + req.return_value.content = return_value + + request = projects.GetProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.Project() + + client.get_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_projects_rest_bad_request(request_type=projects.ListProjectsRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_projects(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.ListProjectsRequest, + dict, + ], +) +def test_list_projects_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = projects.ListProjectsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = projects.ListProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_projects(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_projects_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_list_projects" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_list_projects" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.ListProjectsRequest.pb(projects.ListProjectsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = projects.ListProjectsResponse.to_json( + projects.ListProjectsResponse() + ) + req.return_value.content = return_value + + request = projects.ListProjectsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.ListProjectsResponse() + + client.list_projects( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_projects_rest_bad_request(request_type=projects.SearchProjectsRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search_projects(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.SearchProjectsRequest, + dict, + ], +) +def test_search_projects_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = projects.SearchProjectsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = projects.SearchProjectsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search_projects(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchProjectsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_projects_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_search_projects" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_search_projects" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.SearchProjectsRequest.pb(projects.SearchProjectsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = projects.SearchProjectsResponse.to_json( + projects.SearchProjectsResponse() + ) + req.return_value.content = return_value + + request = projects.SearchProjectsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = projects.SearchProjectsResponse() + + client.search_projects( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_project_rest_bad_request(request_type=projects.CreateProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.CreateProjectRequest, + dict, + ], +) +def test_create_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["project"] = { + "name": "name_value", + "parent": "parent_value", + "project_id": "project_id_value", + "state": 1, + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "etag": "etag_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = projects.CreateProjectRequest.meta.fields["project"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["project"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["project"][field])): + del request_init["project"][field][i][subfield] + else: + del request_init["project"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_project(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectsRestInterceptor, "post_create_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_create_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.CreateProjectRequest.pb(projects.CreateProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = projects.CreateProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_project_rest_bad_request(request_type=projects.UpdateProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": {"name": "projects/sample1"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.UpdateProjectRequest, + dict, + ], +) +def test_update_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": {"name": "projects/sample1"}} + request_init["project"] = { + "name": "projects/sample1", + "parent": "parent_value", + "project_id": "project_id_value", + "state": 1, + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "etag": "etag_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = projects.UpdateProjectRequest.meta.fields["project"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["project"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["project"][field])): + del request_init["project"][field][i][subfield] + else: + del request_init["project"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_project(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectsRestInterceptor, "post_update_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_update_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.UpdateProjectRequest.pb(projects.UpdateProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = projects.UpdateProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_project_rest_bad_request(request_type=projects.MoveProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.move_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.MoveProjectRequest, + dict, + ], +) +def test_move_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.move_project(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectsRestInterceptor, "post_move_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_move_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.MoveProjectRequest.pb(projects.MoveProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = projects.MoveProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.move_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_project_rest_bad_request(request_type=projects.DeleteProjectRequest): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.DeleteProjectRequest, + dict, + ], +) +def test_delete_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_project(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectsRestInterceptor, "post_delete_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_delete_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.DeleteProjectRequest.pb(projects.DeleteProjectRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = projects.DeleteProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_project_rest_bad_request( + request_type=projects.UndeleteProjectRequest, +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.undelete_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + projects.UndeleteProjectRequest, + dict, + ], +) +def test_undelete_project_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.undelete_project(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_project_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectsRestInterceptor, "post_undelete_project" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_undelete_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = projects.UndeleteProjectRequest.pb( + projects.UndeleteProjectRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = projects.UndeleteProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1"} + 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_project_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_projects_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_projects), "__call__") as call: + client.list_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.ListProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_projects_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search_projects), "__call__") as call: + client.search_projects(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.SearchProjectsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_project_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_project), "__call__") as call: + client.create_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.CreateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_project_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_project), "__call__") as call: + client.update_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UpdateProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_move_project_empty_call_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.move_project), "__call__") as call: + client.move_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.MoveProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_project_empty_call_rest(): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_project), "__call__") as call: + client.delete_project(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.DeleteProjectRequest() -def test_test_iam_permissions_rest_error(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProjectsGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_project_empty_call_rest(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProjectsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.undelete_project), "__call__") as call: + client.undelete_project(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProjectsClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = projects.UndeleteProjectRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProjectsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.ProjectsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProjectsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProjectsClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ProjectsGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProjectsGrpcTransport, - transports.ProjectsGrpcAsyncIOTransport, - transports.ProjectsRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProjectsClient.get_transport_class(transport_name)( + +def test_projects_rest_lro_client(): + client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -9284,23 +9612,6 @@ def test_projects_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_projects_rest_lro_client(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -9697,76 +10008,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = ProjectsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9794,7 +10035,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9849,7 +10090,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9896,7 +10137,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProjectsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -9912,22 +10153,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProjectsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProjectsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py index 24886da37256..653bd01a2ae5 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_bindings.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,14 +62,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore -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.resourcemanager_v3.services.tag_bindings import ( TagBindingsAsyncClient, @@ -63,10 +72,24 @@ from google.cloud.resourcemanager_v3.types import tag_bindings +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1132,27 +1155,6 @@ def test_list_tag_bindings(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_tag_bindings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_tag_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListTagBindingsRequest() - - def test_list_tag_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1222,31 +1224,6 @@ def test_list_tag_bindings_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_tag_bindings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tag_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_bindings.ListTagBindingsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_tag_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListTagBindingsRequest() - - @pytest.mark.asyncio async def test_list_tag_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1255,7 +1232,7 @@ async def test_list_tag_bindings_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1294,7 +1271,7 @@ async def test_list_tag_bindings_async( transport: str = "grpc_asyncio", request_type=tag_bindings.ListTagBindingsRequest ): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1373,7 +1350,7 @@ def test_list_tag_bindings_flattened_error(): @pytest.mark.asyncio async def test_list_tag_bindings_flattened_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1404,7 +1381,7 @@ async def test_list_tag_bindings_flattened_async(): @pytest.mark.asyncio async def test_list_tag_bindings_flattened_error_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1515,7 +1492,7 @@ def test_list_tag_bindings_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_tag_bindings_async_pager(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1567,7 +1544,7 @@ async def test_list_tag_bindings_async_pager(): @pytest.mark.asyncio async def test_list_tag_bindings_async_pages(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1650,27 +1627,6 @@ def test_create_tag_binding(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_tag_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_binding), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.CreateTagBindingRequest() - - def test_create_tag_binding_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1741,29 +1697,6 @@ def test_create_tag_binding_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_tag_binding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_tag_binding), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.CreateTagBindingRequest() - - @pytest.mark.asyncio async def test_create_tag_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1772,7 +1705,7 @@ async def test_create_tag_binding_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1816,7 +1749,7 @@ async def test_create_tag_binding_async( transport: str = "grpc_asyncio", request_type=tag_bindings.CreateTagBindingRequest ): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1892,7 +1825,7 @@ def test_create_tag_binding_flattened_error(): @pytest.mark.asyncio async def test_create_tag_binding_flattened_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1923,7 +1856,7 @@ async def test_create_tag_binding_flattened_async(): @pytest.mark.asyncio async def test_create_tag_binding_flattened_error_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1970,27 +1903,6 @@ def test_delete_tag_binding(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_tag_binding_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.DeleteTagBindingRequest() - - def test_delete_tag_binding_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2065,29 +1977,6 @@ def test_delete_tag_binding_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_tag_binding_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_tag_binding), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_tag_binding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.DeleteTagBindingRequest() - - @pytest.mark.asyncio async def test_delete_tag_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2096,7 +1985,7 @@ async def test_delete_tag_binding_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2140,7 +2029,7 @@ async def test_delete_tag_binding_async( transport: str = "grpc_asyncio", request_type=tag_bindings.DeleteTagBindingRequest ): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2207,7 +2096,7 @@ def test_delete_tag_binding_field_headers(): @pytest.mark.asyncio async def test_delete_tag_binding_field_headers_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2281,7 +2170,7 @@ def test_delete_tag_binding_flattened_error(): @pytest.mark.asyncio async def test_delete_tag_binding_flattened_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2312,7 +2201,7 @@ async def test_delete_tag_binding_flattened_async(): @pytest.mark.asyncio async def test_delete_tag_binding_flattened_error_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2362,27 +2251,6 @@ def test_list_effective_tags(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_effective_tags_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_tags), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_effective_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListEffectiveTagsRequest() - - def test_list_effective_tags_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2454,31 +2322,6 @@ def test_list_effective_tags_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_effective_tags_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_effective_tags), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_bindings.ListEffectiveTagsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_effective_tags() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_bindings.ListEffectiveTagsRequest() - - @pytest.mark.asyncio async def test_list_effective_tags_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2487,7 +2330,7 @@ async def test_list_effective_tags_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2526,7 +2369,7 @@ async def test_list_effective_tags_async( transport: str = "grpc_asyncio", request_type=tag_bindings.ListEffectiveTagsRequest ): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2605,7 +2448,7 @@ def test_list_effective_tags_flattened_error(): @pytest.mark.asyncio async def test_list_effective_tags_flattened_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2636,7 +2479,7 @@ async def test_list_effective_tags_flattened_async(): @pytest.mark.asyncio async def test_list_effective_tags_flattened_error_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2747,7 +2590,7 @@ def test_list_effective_tags_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_effective_tags_async_pager(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2799,7 +2642,7 @@ async def test_list_effective_tags_async_pager(): @pytest.mark.asyncio async def test_list_effective_tags_async_pages(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2847,46 +2690,6 @@ async def test_list_effective_tags_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - tag_bindings.ListTagBindingsRequest, - dict, - ], -) -def test_list_tag_bindings_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_bindings.ListTagBindingsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_tag_bindings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagBindingsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_tag_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3034,91 +2837,10 @@ def test_list_tag_bindings_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_bindings_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( +def test_list_tag_bindings_rest_flattened(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_list_tag_bindings" - ) as post, mock.patch.object( - transports.TagBindingsRestInterceptor, "pre_list_tag_bindings" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.ListTagBindingsRequest.pb( - tag_bindings.ListTagBindingsRequest() - ) - 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 = tag_bindings.ListTagBindingsResponse.to_json( - tag_bindings.ListTagBindingsResponse() - ) - - request = tag_bindings.ListTagBindingsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_bindings.ListTagBindingsResponse() - - client.list_tag_bindings( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_bindings_rest_bad_request( - transport: str = "rest", request_type=tag_bindings.ListTagBindingsRequest -): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_tag_bindings(request) - - -def test_list_tag_bindings_rest_flattened(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -3233,114 +2955,6 @@ def test_list_tag_bindings_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - tag_bindings.CreateTagBindingRequest, - dict, - ], -) -def test_create_tag_binding_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_binding"] = { - "name": "name_value", - "parent": "parent_value", - "tag_value": "tag_value_value", - "tag_value_namespaced_name": "tag_value_namespaced_name_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = tag_bindings.CreateTagBindingRequest.meta.fields["tag_binding"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_binding"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_binding"][field])): - del request_init["tag_binding"][field][i][subfield] - else: - del request_init["tag_binding"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_tag_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_tag_binding_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3463,89 +3077,6 @@ def test_create_tag_binding_rest_unset_required_fields(): assert set(unset_fields) == (set(("validateOnly",)) & set(("tagBinding",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_binding_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagBindingsRestInterceptor, "post_create_tag_binding" - ) as post, mock.patch.object( - transports.TagBindingsRestInterceptor, "pre_create_tag_binding" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.CreateTagBindingRequest.pb( - tag_bindings.CreateTagBindingRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_bindings.CreateTagBindingRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_binding( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_binding_rest_bad_request( - transport: str = "rest", request_type=tag_bindings.CreateTagBindingRequest -): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.create_tag_binding(request) - - def test_create_tag_binding_rest_flattened(): client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3599,59 +3130,18 @@ def test_create_tag_binding_rest_flattened_error(transport: str = "rest"): ) -def test_create_tag_binding_rest_error(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_delete_tag_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - tag_bindings.DeleteTagBindingRequest, - dict, - ], -) -def test_delete_tag_binding_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagBindings/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_tag_binding(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_tag_binding_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( @@ -3764,89 +3254,6 @@ def test_delete_tag_binding_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_binding_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagBindingsRestInterceptor, "post_delete_tag_binding" - ) as post, mock.patch.object( - transports.TagBindingsRestInterceptor, "pre_delete_tag_binding" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.DeleteTagBindingRequest.pb( - tag_bindings.DeleteTagBindingRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_bindings.DeleteTagBindingRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_binding( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_binding_rest_bad_request( - transport: str = "rest", request_type=tag_bindings.DeleteTagBindingRequest -): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagBindings/sample1"} - 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.delete_tag_binding(request) - - def test_delete_tag_binding_rest_flattened(): client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3900,52 +3307,6 @@ def test_delete_tag_binding_rest_flattened_error(transport: str = "rest"): ) -def test_delete_tag_binding_rest_error(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_bindings.ListEffectiveTagsRequest, - dict, - ], -) -def test_list_effective_tags_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_bindings.ListEffectiveTagsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_bindings.ListEffectiveTagsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_effective_tags(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEffectiveTagsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_effective_tags_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4095,87 +3456,6 @@ def test_list_effective_tags_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_effective_tags_rest_interceptors(null_interceptor): - transport = transports.TagBindingsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.TagBindingsRestInterceptor(), - ) - client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_list_effective_tags" - ) as post, mock.patch.object( - transports.TagBindingsRestInterceptor, "pre_list_effective_tags" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_bindings.ListEffectiveTagsRequest.pb( - tag_bindings.ListEffectiveTagsRequest() - ) - 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 = tag_bindings.ListEffectiveTagsResponse.to_json( - tag_bindings.ListEffectiveTagsResponse() - ) - - request = tag_bindings.ListEffectiveTagsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_bindings.ListEffectiveTagsResponse() - - client.list_effective_tags( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_effective_tags_rest_bad_request( - transport: str = "rest", request_type=tag_bindings.ListEffectiveTagsRequest -): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_effective_tags(request) - - def test_list_effective_tags_rest_flattened(): client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4283,121 +3563,1061 @@ def test_list_effective_tags_rest_pager(transport: str = "rest"): sample_request = {} - pager = client.list_effective_tags(request=sample_request) + pager = client.list_effective_tags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_bindings.EffectiveTag) for i in results) + + pages = list(client.list_effective_tags(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagBindingsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagBindingsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagBindingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagBindingsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagBindingsGrpcTransport, + transports.TagBindingsGrpcAsyncIOTransport, + transports.TagBindingsRestTransport, + ], +) +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_transport_kind_grpc(): + transport = TagBindingsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_bindings_empty_call_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), "__call__" + ) as call: + call.return_value = tag_bindings.ListTagBindingsResponse() + client.list_tag_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListTagBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_binding_empty_call_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.CreateTagBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_binding_empty_call_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.DeleteTagBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_effective_tags_empty_call_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_tags), "__call__" + ) as call: + call.return_value = tag_bindings.ListEffectiveTagsResponse() + client.list_effective_tags(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListEffectiveTagsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TagBindingsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tag_bindings_empty_call_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_bindings.ListTagBindingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tag_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListTagBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tag_binding_empty_call_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.CreateTagBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tag_binding_empty_call_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.DeleteTagBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_effective_tags_empty_call_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_tags), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_bindings.ListEffectiveTagsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_effective_tags(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListEffectiveTagsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TagBindingsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_tag_bindings_rest_bad_request( + request_type=tag_bindings.ListTagBindingsRequest, +): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_tag_bindings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_bindings.ListTagBindingsRequest, + dict, + ], +) +def test_list_tag_bindings_rest_call_success(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_bindings.ListTagBindingsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_bindings.ListTagBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tag_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagBindingsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_bindings_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_list_tag_bindings" + ) as post, mock.patch.object( + transports.TagBindingsRestInterceptor, "pre_list_tag_bindings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.ListTagBindingsRequest.pb( + tag_bindings.ListTagBindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_bindings.ListTagBindingsResponse.to_json( + tag_bindings.ListTagBindingsResponse() + ) + req.return_value.content = return_value + + request = tag_bindings.ListTagBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_bindings.ListTagBindingsResponse() + + client.list_tag_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_binding_rest_bad_request( + request_type=tag_bindings.CreateTagBindingRequest, +): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_tag_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_bindings.CreateTagBindingRequest, + dict, + ], +) +def test_create_tag_binding_rest_call_success(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_binding"] = { + "name": "name_value", + "parent": "parent_value", + "tag_value": "tag_value_value", + "tag_value_namespaced_name": "tag_value_namespaced_name_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_bindings.CreateTagBindingRequest.meta.fields["tag_binding"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_binding"][field])): + del request_init["tag_binding"][field][i][subfield] + else: + del request_init["tag_binding"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_tag_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_binding_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagBindingsRestInterceptor, "post_create_tag_binding" + ) as post, mock.patch.object( + transports.TagBindingsRestInterceptor, "pre_create_tag_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.CreateTagBindingRequest.pb( + tag_bindings.CreateTagBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_bindings.CreateTagBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_binding_rest_bad_request( + request_type=tag_bindings.DeleteTagBindingRequest, +): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagBindings/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_tag_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_bindings.DeleteTagBindingRequest, + dict, + ], +) +def test_delete_tag_binding_rest_call_success(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagBindings/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_tag_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_binding_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagBindingsRestInterceptor, "post_delete_tag_binding" + ) as post, mock.patch.object( + transports.TagBindingsRestInterceptor, "pre_delete_tag_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.DeleteTagBindingRequest.pb( + tag_bindings.DeleteTagBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_bindings.DeleteTagBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_effective_tags_rest_bad_request( + request_type=tag_bindings.ListEffectiveTagsRequest, +): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_effective_tags(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_bindings.ListEffectiveTagsRequest, + dict, + ], +) +def test_list_effective_tags_rest_call_success(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_bindings.ListEffectiveTagsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_bindings.ListEffectiveTagsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_effective_tags(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEffectiveTagsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_effective_tags_rest_interceptors(null_interceptor): + transport = transports.TagBindingsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.TagBindingsRestInterceptor(), + ) + client = TagBindingsClient(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.TagBindingsRestInterceptor, "post_list_effective_tags" + ) as post, mock.patch.object( + transports.TagBindingsRestInterceptor, "pre_list_effective_tags" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_bindings.ListEffectiveTagsRequest.pb( + tag_bindings.ListEffectiveTagsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_bindings.ListEffectiveTagsResponse.to_json( + tag_bindings.ListEffectiveTagsResponse() + ) + req.return_value.content = return_value + + request = tag_bindings.ListEffectiveTagsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_bindings.ListEffectiveTagsResponse() + + client.list_effective_tags( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_bindings.EffectiveTag) for i in results) + response = client.get_operation(request) - pages = list(client.list_effective_tags(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +def test_initialize_client_w_rest(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert client is not None - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.TagBindingsGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_bindings_empty_call_rest(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_tag_bindings), "__call__" + ) as call: + client.list_tag_bindings(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.TagBindingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagBindingsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListTagBindingsRequest() + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagBindingsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_binding_empty_call_rest(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = TagBindingsClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_tag_binding), "__call__" + ) as call: + client.create_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.CreateTagBindingRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagBindingsGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_binding_empty_call_rest(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.TagBindingsGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_tag_binding), "__call__" + ) as call: + client.delete_tag_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.DeleteTagBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_effective_tags_empty_call_rest(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_effective_tags), "__call__" + ) as call: + client.list_effective_tags(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagBindingsGrpcTransport, - transports.TagBindingsGrpcAsyncIOTransport, - transports.TagBindingsRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_bindings.ListEffectiveTagsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = TagBindingsClient.get_transport_class(transport_name)( + +def test_tag_bindings_rest_lro_client(): + client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -4647,23 +4867,6 @@ def test_tag_bindings_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_tag_bindings_rest_lro_client(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -5079,76 +5282,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = TagBindingsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5176,7 +5309,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5231,7 +5364,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5278,7 +5411,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = TagBindingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5294,22 +5427,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = TagBindingsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = TagBindingsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = TagBindingsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_holds.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_holds.py index da9dcfcf669e..2ab1c190741f 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_holds.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_holds.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,15 +62,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.resourcemanager_v3.services.tag_holds import ( TagHoldsAsyncClient, @@ -64,10 +73,24 @@ from google.cloud.resourcemanager_v3.types import tag_holds +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1109,25 +1132,6 @@ def test_create_tag_hold(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_tag_hold_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_hold), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_tag_hold() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.CreateTagHoldRequest() - - def test_create_tag_hold_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1196,27 +1200,6 @@ def test_create_tag_hold_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_tag_hold_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_hold), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_tag_hold() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.CreateTagHoldRequest() - - @pytest.mark.asyncio async def test_create_tag_hold_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1225,7 +1208,7 @@ async def test_create_tag_hold_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1269,7 +1252,7 @@ async def test_create_tag_hold_async( transport: str = "grpc_asyncio", request_type=tag_holds.CreateTagHoldRequest ): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1332,7 +1315,7 @@ def test_create_tag_hold_field_headers(): @pytest.mark.asyncio async def test_create_tag_hold_field_headers_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1407,7 +1390,7 @@ def test_create_tag_hold_flattened_error(): @pytest.mark.asyncio async def test_create_tag_hold_flattened_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1440,7 +1423,7 @@ async def test_create_tag_hold_flattened_async(): @pytest.mark.asyncio async def test_create_tag_hold_flattened_error_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1486,25 +1469,6 @@ def test_delete_tag_hold(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_tag_hold_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_hold), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_tag_hold() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.DeleteTagHoldRequest() - - def test_delete_tag_hold_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1573,27 +1537,6 @@ def test_delete_tag_hold_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_tag_hold_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_hold), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_tag_hold() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.DeleteTagHoldRequest() - - @pytest.mark.asyncio async def test_delete_tag_hold_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1602,7 +1545,7 @@ async def test_delete_tag_hold_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1646,7 +1589,7 @@ async def test_delete_tag_hold_async( transport: str = "grpc_asyncio", request_type=tag_holds.DeleteTagHoldRequest ): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1709,7 +1652,7 @@ def test_delete_tag_hold_field_headers(): @pytest.mark.asyncio async def test_delete_tag_hold_field_headers_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1779,7 +1722,7 @@ def test_delete_tag_hold_flattened_error(): @pytest.mark.asyncio async def test_delete_tag_hold_flattened_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1808,7 +1751,7 @@ async def test_delete_tag_hold_flattened_async(): @pytest.mark.asyncio async def test_delete_tag_hold_flattened_error_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1856,25 +1799,6 @@ def test_list_tag_holds(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_tag_holds_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_holds), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_tag_holds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.ListTagHoldsRequest() - - def test_list_tag_holds_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1942,29 +1866,6 @@ def test_list_tag_holds_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_tag_holds_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_holds), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_holds.ListTagHoldsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_tag_holds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_holds.ListTagHoldsRequest() - - @pytest.mark.asyncio async def test_list_tag_holds_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1973,7 +1874,7 @@ async def test_list_tag_holds_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2012,7 +1913,7 @@ async def test_list_tag_holds_async( transport: str = "grpc_asyncio", request_type=tag_holds.ListTagHoldsRequest ): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2078,7 +1979,7 @@ def test_list_tag_holds_field_headers(): @pytest.mark.asyncio async def test_list_tag_holds_field_headers_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2148,7 +2049,7 @@ def test_list_tag_holds_flattened_error(): @pytest.mark.asyncio async def test_list_tag_holds_flattened_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2177,7 +2078,7 @@ async def test_list_tag_holds_flattened_async(): @pytest.mark.asyncio async def test_list_tag_holds_flattened_error_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2287,7 +2188,7 @@ def test_list_tag_holds_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_tag_holds_async_pager(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2337,7 +2238,7 @@ async def test_list_tag_holds_async_pager(): @pytest.mark.asyncio async def test_list_tag_holds_async_pages(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2383,115 +2284,6 @@ async def test_list_tag_holds_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - tag_holds.CreateTagHoldRequest, - dict, - ], -) -def test_create_tag_hold_rest(request_type): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "tagValues/sample1"} - request_init["tag_hold"] = { - "name": "name_value", - "holder": "holder_value", - "origin": "origin_value", - "help_link": "help_link_value", - "create_time": {"seconds": 751, "nanos": 543}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = tag_holds.CreateTagHoldRequest.meta.fields["tag_hold"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_hold"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_hold"][field])): - del request_init["tag_hold"][field][i][subfield] - else: - del request_init["tag_hold"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_tag_hold(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_tag_hold_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2623,89 +2415,10 @@ def test_create_tag_hold_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_hold_rest_interceptors(null_interceptor): - transport = transports.TagHoldsRestTransport( +def test_create_tag_hold_rest_flattened(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), - ) - client = TagHoldsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagHoldsRestInterceptor, "post_create_tag_hold" - ) as post, mock.patch.object( - transports.TagHoldsRestInterceptor, "pre_create_tag_hold" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_holds.CreateTagHoldRequest.pb(tag_holds.CreateTagHoldRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_holds.CreateTagHoldRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_hold( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_hold_rest_bad_request( - transport: str = "rest", request_type=tag_holds.CreateTagHoldRequest -): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "tagValues/sample1"} - 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.create_tag_hold(request) - - -def test_create_tag_hold_rest_flattened(): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -2757,47 +2470,6 @@ def test_create_tag_hold_rest_flattened_error(transport: str = "rest"): ) -def test_create_tag_hold_rest_error(): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_holds.DeleteTagHoldRequest, - dict, - ], -) -def test_delete_tag_hold_rest(request_type): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1/tagHolds/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_tag_hold(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_tag_hold_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2920,85 +2592,6 @@ def test_delete_tag_hold_rest_unset_required_fields(): assert set(unset_fields) == (set(("validateOnly",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_hold_rest_interceptors(null_interceptor): - transport = transports.TagHoldsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), - ) - client = TagHoldsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagHoldsRestInterceptor, "post_delete_tag_hold" - ) as post, mock.patch.object( - transports.TagHoldsRestInterceptor, "pre_delete_tag_hold" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_holds.DeleteTagHoldRequest.pb(tag_holds.DeleteTagHoldRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_holds.DeleteTagHoldRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_hold( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_hold_rest_bad_request( - transport: str = "rest", request_type=tag_holds.DeleteTagHoldRequest -): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1/tagHolds/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.delete_tag_hold(request) - - def test_delete_tag_hold_rest_flattened(): client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3052,52 +2645,6 @@ def test_delete_tag_hold_rest_flattened_error(transport: str = "rest"): ) -def test_delete_tag_hold_rest_error(): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_holds.ListTagHoldsRequest, - dict, - ], -) -def test_list_tag_holds_rest(request_type): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "tagValues/sample1"} - 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 = tag_holds.ListTagHoldsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_holds.ListTagHoldsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_tag_holds(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagHoldsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_tag_holds_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3234,93 +2781,16 @@ def test_list_tag_holds_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_holds_rest_interceptors(null_interceptor): - transport = transports.TagHoldsRestTransport( +def test_list_tag_holds_rest_flattened(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), + transport="rest", ) - client = TagHoldsClient(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.TagHoldsRestInterceptor, "post_list_tag_holds" - ) as post, mock.patch.object( - transports.TagHoldsRestInterceptor, "pre_list_tag_holds" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_holds.ListTagHoldsRequest.pb(tag_holds.ListTagHoldsRequest()) - 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 = tag_holds.ListTagHoldsResponse.to_json( - tag_holds.ListTagHoldsResponse() - ) - - request = tag_holds.ListTagHoldsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_holds.ListTagHoldsResponse() - - client.list_tag_holds( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_holds_rest_bad_request( - transport: str = "rest", request_type=tag_holds.ListTagHoldsRequest -): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "tagValues/sample1"} - 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.list_tag_holds(request) - - -def test_list_tag_holds_rest_flattened(): - client = TagHoldsClient( - 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 = tag_holds.ListTagHoldsResponse() + # 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 = tag_holds.ListTagHoldsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "tagValues/sample1"} @@ -3414,123 +2884,833 @@ def test_list_tag_holds_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "tagValues/sample1"} + sample_request = {"parent": "tagValues/sample1"} + + pager = client.list_tag_holds(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tag_holds.TagHold) for i in results) + + pages = list(client.list_tag_holds(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagHoldsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagHoldsClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagHoldsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagHoldsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagHoldsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagHoldsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagHoldsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagHoldsGrpcTransport, + transports.TagHoldsGrpcAsyncIOTransport, + transports.TagHoldsRestTransport, + ], +) +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_transport_kind_grpc(): + transport = TagHoldsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_hold_empty_call_grpc(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_hold), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_tag_hold(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.CreateTagHoldRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_hold_empty_call_grpc(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_hold), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_tag_hold(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.DeleteTagHoldRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_holds_empty_call_grpc(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_holds), "__call__") as call: + call.return_value = tag_holds.ListTagHoldsResponse() + client.list_tag_holds(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.ListTagHoldsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TagHoldsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TagHoldsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tag_hold_empty_call_grpc_asyncio(): + client = TagHoldsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_hold), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_tag_hold(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.CreateTagHoldRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tag_hold_empty_call_grpc_asyncio(): + client = TagHoldsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_hold), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_tag_hold(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.DeleteTagHoldRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tag_holds_empty_call_grpc_asyncio(): + client = TagHoldsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_holds), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_holds.ListTagHoldsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tag_holds(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.ListTagHoldsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TagHoldsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_tag_hold_rest_bad_request(request_type=tag_holds.CreateTagHoldRequest): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_tag_hold(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_holds.CreateTagHoldRequest, + dict, + ], +) +def test_create_tag_hold_rest_call_success(request_type): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "tagValues/sample1"} + request_init["tag_hold"] = { + "name": "name_value", + "holder": "holder_value", + "origin": "origin_value", + "help_link": "help_link_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_holds.CreateTagHoldRequest.meta.fields["tag_hold"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_hold"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_hold"][field])): + del request_init["tag_hold"][field][i][subfield] + else: + del request_init["tag_hold"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_tag_hold(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_hold_rest_interceptors(null_interceptor): + transport = transports.TagHoldsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), + ) + client = TagHoldsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagHoldsRestInterceptor, "post_create_tag_hold" + ) as post, mock.patch.object( + transports.TagHoldsRestInterceptor, "pre_create_tag_hold" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_holds.CreateTagHoldRequest.pb(tag_holds.CreateTagHoldRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_holds.CreateTagHoldRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_hold( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_hold_rest_bad_request(request_type=tag_holds.DeleteTagHoldRequest): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1/tagHolds/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_tag_hold(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_holds.DeleteTagHoldRequest, + dict, + ], +) +def test_delete_tag_hold_rest_call_success(request_type): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1/tagHolds/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_tag_hold(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_hold_rest_interceptors(null_interceptor): + transport = transports.TagHoldsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), + ) + client = TagHoldsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagHoldsRestInterceptor, "post_delete_tag_hold" + ) as post, mock.patch.object( + transports.TagHoldsRestInterceptor, "pre_delete_tag_hold" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_holds.DeleteTagHoldRequest.pb(tag_holds.DeleteTagHoldRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_holds.DeleteTagHoldRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_hold( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tag_holds_rest_bad_request(request_type=tag_holds.ListTagHoldsRequest): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_tag_holds(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_holds.ListTagHoldsRequest, + dict, + ], +) +def test_list_tag_holds_rest_call_success(request_type): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "tagValues/sample1"} + 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 = tag_holds.ListTagHoldsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_holds.ListTagHoldsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tag_holds(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagHoldsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_holds_rest_interceptors(null_interceptor): + transport = transports.TagHoldsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagHoldsRestInterceptor(), + ) + client = TagHoldsClient(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.TagHoldsRestInterceptor, "post_list_tag_holds" + ) as post, mock.patch.object( + transports.TagHoldsRestInterceptor, "pre_list_tag_holds" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_holds.ListTagHoldsRequest.pb(tag_holds.ListTagHoldsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_holds.ListTagHoldsResponse.to_json( + tag_holds.ListTagHoldsResponse() + ) + req.return_value.content = return_value + + request = tag_holds.ListTagHoldsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_holds.ListTagHoldsResponse() + + client.list_tag_holds( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() - pager = client.list_tag_holds(request=sample_request) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tag_holds.TagHold) for i in results) + req.return_value = response_value - pages = list(client.list_tag_holds(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + response = client.get_operation(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagHoldsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagHoldsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +def test_initialize_client_w_rest(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = TagHoldsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + assert client is not None - # It is an error to provide an api_key and a transport instance. - transport = transports.TagHoldsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_hold_empty_call_rest(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagHoldsClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagHoldsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_hold), "__call__") as call: + client.create_tag_hold(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.TagHoldsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagHoldsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.CreateTagHoldRequest() + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagHoldsGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_hold_empty_call_rest(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = TagHoldsClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_hold), "__call__") as call: + client.delete_tag_hold(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagHoldsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.DeleteTagHoldRequest() - transport = transports.TagHoldsGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_holds_empty_call_rest(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_holds), "__call__") as call: + client.list_tag_holds(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagHoldsGrpcTransport, - transports.TagHoldsGrpcAsyncIOTransport, - transports.TagHoldsRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_holds.ListTagHoldsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = TagHoldsClient.get_transport_class(transport_name)( + +def test_tag_holds_rest_lro_client(): + client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -3779,23 +3959,6 @@ def test_tag_holds_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_tag_holds_rest_lro_client(): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -4171,76 +4334,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = TagHoldsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4268,7 +4361,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4323,7 +4416,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4370,7 +4463,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = TagHoldsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -4386,22 +4479,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = TagHoldsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = TagHoldsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = TagHoldsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py index dd90971206d4..f5d286f23f43 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_keys.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,16 +65,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import expr_pb2 # type: ignore -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.resourcemanager_v3.services.tag_keys import ( TagKeysAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.resourcemanager_v3.types import tag_keys +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1107,25 +1130,6 @@ def test_list_tag_keys(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_tag_keys_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_keys), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_tag_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.ListTagKeysRequest() - - def test_list_tag_keys_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1191,29 +1195,6 @@ def test_list_tag_keys_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_tag_keys_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_keys), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_keys.ListTagKeysResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_tag_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.ListTagKeysRequest() - - @pytest.mark.asyncio async def test_list_tag_keys_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1222,7 +1203,7 @@ async def test_list_tag_keys_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1261,7 +1242,7 @@ async def test_list_tag_keys_async( transport: str = "grpc_asyncio", request_type=tag_keys.ListTagKeysRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1336,7 +1317,7 @@ def test_list_tag_keys_flattened_error(): @pytest.mark.asyncio async def test_list_tag_keys_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1365,7 +1346,7 @@ async def test_list_tag_keys_flattened_async(): @pytest.mark.asyncio async def test_list_tag_keys_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1472,7 +1453,7 @@ def test_list_tag_keys_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_tag_keys_async_pager(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1522,7 +1503,7 @@ async def test_list_tag_keys_async_pager(): @pytest.mark.asyncio async def test_list_tag_keys_async_pages(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1616,25 +1597,6 @@ def test_get_tag_key(request_type, transport: str = "grpc"): assert response.purpose == tag_keys.Purpose.GCE_FIREWALL -def test_get_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_tag_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetTagKeyRequest() - - def test_get_tag_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1698,35 +1660,6 @@ def test_get_tag_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_tag_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_tag_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_keys.TagKey( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - purpose=tag_keys.Purpose.GCE_FIREWALL, - ) - ) - response = await client.get_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetTagKeyRequest() - - @pytest.mark.asyncio async def test_get_tag_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1735,7 +1668,7 @@ async def test_get_tag_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1774,7 +1707,7 @@ async def test_get_tag_key_async( transport: str = "grpc_asyncio", request_type=tag_keys.GetTagKeyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1852,7 +1785,7 @@ def test_get_tag_key_field_headers(): @pytest.mark.asyncio async def test_get_tag_key_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1920,7 +1853,7 @@ def test_get_tag_key_flattened_error(): @pytest.mark.asyncio async def test_get_tag_key_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1947,7 +1880,7 @@ async def test_get_tag_key_flattened_async(): @pytest.mark.asyncio async def test_get_tag_key_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2009,27 +1942,6 @@ def test_get_namespaced_tag_key(request_type, transport: str = "grpc"): assert response.purpose == tag_keys.Purpose.GCE_FIREWALL -def test_get_namespaced_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespaced_tag_key), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_namespaced_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetNamespacedTagKeyRequest() - - def test_get_namespaced_tag_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2100,37 +2012,6 @@ def test_get_namespaced_tag_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_namespaced_tag_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespaced_tag_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_keys.TagKey( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - purpose=tag_keys.Purpose.GCE_FIREWALL, - ) - ) - response = await client.get_namespaced_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.GetNamespacedTagKeyRequest() - - @pytest.mark.asyncio async def test_get_namespaced_tag_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2139,7 +2020,7 @@ async def test_get_namespaced_tag_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2178,7 +2059,7 @@ async def test_get_namespaced_tag_key_async( transport: str = "grpc_asyncio", request_type=tag_keys.GetNamespacedTagKeyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2269,7 +2150,7 @@ def test_get_namespaced_tag_key_flattened_error(): @pytest.mark.asyncio async def test_get_namespaced_tag_key_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2298,7 +2179,7 @@ async def test_get_namespaced_tag_key_flattened_async(): @pytest.mark.asyncio async def test_get_namespaced_tag_key_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2343,25 +2224,6 @@ def test_create_tag_key(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.CreateTagKeyRequest() - - def test_create_tag_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2426,27 +2288,6 @@ def test_create_tag_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_tag_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.CreateTagKeyRequest() - - @pytest.mark.asyncio async def test_create_tag_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2455,7 +2296,7 @@ async def test_create_tag_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2499,7 +2340,7 @@ async def test_create_tag_key_async( transport: str = "grpc_asyncio", request_type=tag_keys.CreateTagKeyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2571,7 +2412,7 @@ def test_create_tag_key_flattened_error(): @pytest.mark.asyncio async def test_create_tag_key_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2600,7 +2441,7 @@ async def test_create_tag_key_flattened_async(): @pytest.mark.asyncio async def test_create_tag_key_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2645,25 +2486,6 @@ def test_update_tag_key(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_tag_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.UpdateTagKeyRequest() - - def test_update_tag_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2728,27 +2550,6 @@ def test_update_tag_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_tag_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_tag_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.UpdateTagKeyRequest() - - @pytest.mark.asyncio async def test_update_tag_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2757,7 +2558,7 @@ async def test_update_tag_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2801,7 +2602,7 @@ async def test_update_tag_key_async( transport: str = "grpc_asyncio", request_type=tag_keys.UpdateTagKeyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2864,7 +2665,7 @@ def test_update_tag_key_field_headers(): @pytest.mark.asyncio async def test_update_tag_key_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2939,7 +2740,7 @@ def test_update_tag_key_flattened_error(): @pytest.mark.asyncio async def test_update_tag_key_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2972,7 +2773,7 @@ async def test_update_tag_key_flattened_async(): @pytest.mark.asyncio async def test_update_tag_key_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3018,25 +2819,6 @@ def test_delete_tag_key(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_tag_key_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_key), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.DeleteTagKeyRequest() - - def test_delete_tag_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3107,27 +2889,6 @@ def test_delete_tag_key_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_tag_key_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_key), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_tag_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_keys.DeleteTagKeyRequest() - - @pytest.mark.asyncio async def test_delete_tag_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3136,7 +2897,7 @@ async def test_delete_tag_key_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3180,7 +2941,7 @@ async def test_delete_tag_key_async( transport: str = "grpc_asyncio", request_type=tag_keys.DeleteTagKeyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3243,7 +3004,7 @@ def test_delete_tag_key_field_headers(): @pytest.mark.asyncio async def test_delete_tag_key_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3313,7 +3074,7 @@ def test_delete_tag_key_flattened_error(): @pytest.mark.asyncio async def test_delete_tag_key_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3342,7 +3103,7 @@ async def test_delete_tag_key_flattened_async(): @pytest.mark.asyncio async def test_delete_tag_key_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3392,25 +3153,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3474,30 +3216,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3506,7 +3224,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3545,7 +3263,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3613,7 +3331,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3698,7 +3416,7 @@ def test_get_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3725,7 +3443,7 @@ async def test_get_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3775,25 +3493,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3857,30 +3556,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3889,7 +3564,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3928,7 +3603,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3996,7 +3671,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4082,7 +3757,7 @@ def test_set_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4109,7 +3784,7 @@ async def test_set_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4159,27 +3834,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4249,31 +3903,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4282,7 +3911,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4322,7 +3951,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4392,7 +4021,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4490,7 +4119,7 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4525,7 +4154,7 @@ async def test_test_iam_permissions_flattened_async(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4538,46 +4167,6 @@ async def test_test_iam_permissions_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.ListTagKeysRequest, - dict, - ], -) -def test_list_tag_keys_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_keys.ListTagKeysResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_keys.ListTagKeysResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_tag_keys(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagKeysPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_tag_keys_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4721,83 +4310,6 @@ def test_list_tag_keys_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_keys_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_list_tag_keys" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_list_tag_keys" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.ListTagKeysRequest.pb(tag_keys.ListTagKeysRequest()) - 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 = tag_keys.ListTagKeysResponse.to_json( - tag_keys.ListTagKeysResponse() - ) - - request = tag_keys.ListTagKeysRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_keys.ListTagKeysResponse() - - client.list_tag_keys( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_keys_rest_bad_request( - transport: str = "rest", request_type=tag_keys.ListTagKeysRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_tag_keys(request) - - def test_list_tag_keys_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4912,66 +4424,14 @@ def test_list_tag_keys_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.GetTagKeyRequest, - dict, - ], -) -def test_get_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagKeys/sample1"} - 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 = tag_keys.TagKey( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - purpose=tag_keys.Purpose.GCE_FIREWALL, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_keys.TagKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_tag_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_keys.TagKey) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.short_name == "short_name_value" - assert response.namespaced_name == "namespaced_name_value" - assert response.description == "description_value" - assert response.etag == "etag_value" - assert response.purpose == tag_keys.Purpose.GCE_FIREWALL - - -def test_get_tag_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_tag_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -5081,81 +4541,6 @@ def test_get_tag_key_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_tag_key" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_get_tag_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.GetTagKeyRequest.pb(tag_keys.GetTagKeyRequest()) - 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 = tag_keys.TagKey.to_json(tag_keys.TagKey()) - - request = tag_keys.GetTagKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_keys.TagKey() - - client.get_tag_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tag_key_rest_bad_request( - transport: str = "rest", request_type=tag_keys.GetTagKeyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagKeys/sample1"} - 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_tag_key(request) - - def test_get_tag_key_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5211,64 +4596,6 @@ def test_get_tag_key_rest_flattened_error(transport: str = "rest"): ) -def test_get_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.GetNamespacedTagKeyRequest, - dict, - ], -) -def test_get_namespaced_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_keys.TagKey( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - purpose=tag_keys.Purpose.GCE_FIREWALL, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_keys.TagKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_namespaced_tag_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_keys.TagKey) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.short_name == "short_name_value" - assert response.namespaced_name == "namespaced_name_value" - assert response.description == "description_value" - assert response.etag == "etag_value" - assert response.purpose == tag_keys.Purpose.GCE_FIREWALL - - def test_get_namespaced_tag_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5404,83 +4731,6 @@ def test_get_namespaced_tag_key_rest_unset_required_fields(): assert set(unset_fields) == (set(("name",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_namespaced_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_namespaced_tag_key" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_get_namespaced_tag_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.GetNamespacedTagKeyRequest.pb( - tag_keys.GetNamespacedTagKeyRequest() - ) - 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 = tag_keys.TagKey.to_json(tag_keys.TagKey()) - - request = tag_keys.GetNamespacedTagKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_keys.TagKey() - - client.get_namespaced_tag_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_namespaced_tag_key_rest_bad_request( - transport: str = "rest", request_type=tag_keys.GetNamespacedTagKeyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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_namespaced_tag_key(request) - - def test_get_namespaced_tag_key_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5536,138 +4786,18 @@ def test_get_namespaced_tag_key_rest_flattened_error(transport: str = "rest"): ) -def test_get_namespaced_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_tag_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.CreateTagKeyRequest, - dict, - ], -) -def test_create_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_key"] = { - "name": "name_value", - "parent": "parent_value", - "short_name": "short_name_value", - "namespaced_name": "namespaced_name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "etag": "etag_value", - "purpose": 1, - "purpose_data": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = tag_keys.CreateTagKeyRequest.meta.fields["tag_key"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_key"][field])): - del request_init["tag_key"][field][i][subfield] - else: - del request_init["tag_key"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_tag_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.create_tag_key in client._transport._wrapped_methods @@ -5772,85 +4902,6 @@ def test_create_tag_key_rest_unset_required_fields(): assert set(unset_fields) == (set(("validateOnly",)) & set(("tagKey",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagKeysRestInterceptor, "post_create_tag_key" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_create_tag_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.CreateTagKeyRequest.pb(tag_keys.CreateTagKeyRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_keys.CreateTagKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_key_rest_bad_request( - transport: str = "rest", request_type=tag_keys.CreateTagKeyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.create_tag_key(request) - - def test_create_tag_key_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5902,151 +4953,31 @@ def test_create_tag_key_rest_flattened_error(transport: str = "rest"): ) -def test_create_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_tag_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.UpdateTagKeyRequest, - dict, - ], -) -def test_update_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.update_tag_key in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = {"tag_key": {"name": "tagKeys/sample1"}} - request_init["tag_key"] = { - "name": "tagKeys/sample1", - "parent": "parent_value", - "short_name": "short_name_value", - "namespaced_name": "namespaced_name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "etag": "etag_value", - "purpose": 1, - "purpose_data": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_tag_key] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = tag_keys.UpdateTagKeyRequest.meta.fields["tag_key"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_key"][field])): - del request_init["tag_key"][field][i][subfield] - else: - del request_init["tag_key"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_tag_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_tag_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_tag_key] = mock_rpc - - request = {} - client.update_tag_key(request) + request = {} + client.update_tag_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6151,85 +5082,6 @@ def test_update_tag_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagKeysRestInterceptor, "post_update_tag_key" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_update_tag_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.UpdateTagKeyRequest.pb(tag_keys.UpdateTagKeyRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_keys.UpdateTagKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tag_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tag_key_rest_bad_request( - transport: str = "rest", request_type=tag_keys.UpdateTagKeyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"tag_key": {"name": "tagKeys/sample1"}} - 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_tag_key(request) - - def test_update_tag_key_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6285,47 +5137,6 @@ def test_update_tag_key_rest_flattened_error(transport: str = "rest"): ) -def test_update_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_keys.DeleteTagKeyRequest, - dict, - ], -) -def test_delete_tag_key_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagKeys/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_tag_key(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_tag_key_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6459,104 +5270,25 @@ def test_delete_tag_key_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_key_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( +def test_delete_tag_key_rest_flattened(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + transport="rest", ) - client = TagKeysClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagKeysRestInterceptor, "post_delete_tag_key" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_delete_tag_key" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_keys.DeleteTagKeyRequest.pb(tag_keys.DeleteTagKeyRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() + # 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "tagKeys/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - request = tag_keys.DeleteTagKeyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_key( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_key_rest_bad_request( - transport: str = "rest", request_type=tag_keys.DeleteTagKeyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagKeys/sample1"} - 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.delete_tag_key(request) - - -def test_delete_tag_key_rest_flattened(): - client = TagKeysClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "tagKeys/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6591,52 +5323,6 @@ def test_delete_tag_key_rest_flattened_error(transport: str = "rest"): ) -def test_delete_tag_key_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6755,81 +5441,6 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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_iam_policy(request) - - def test_get_iam_policy_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6883,52 +5494,6 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_get_iam_policy_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7055,91 +5620,16 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( +def test_set_iam_policy_rest_flattened(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + transport="rest", ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = TagKeysClient( - 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 = policy_pb2.Policy() + # 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 = policy_pb2.Policy() # get arguments that satisfy an http rule for this method sample_request = {"resource": "tagKeys/sample1"} @@ -7183,50 +5673,6 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_set_iam_policy_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7361,83 +5807,6 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.TagKeysRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), - ) - client = TagKeysClient(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.TagKeysRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.TagKeysRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagKeys/sample1"} - 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.test_iam_permissions(request) - - def test_test_iam_permissions_rest_flattened(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7478,132 +5847,2057 @@ def test_test_iam_permissions_rest_flattened(): ) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = TagKeysClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagKeysClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagKeysClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagKeysClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagKeysClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagKeysGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagKeysGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagKeysGrpcTransport, + transports.TagKeysGrpcAsyncIOTransport, + transports.TagKeysRestTransport, + ], +) +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_transport_kind_grpc(): + transport = TagKeysClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_keys_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_keys), "__call__") as call: + call.return_value = tag_keys.ListTagKeysResponse() + client.list_tag_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.ListTagKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tag_key_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_key), "__call__") as call: + call.return_value = tag_keys.TagKey() + client.get_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_namespaced_tag_key_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_key), "__call__" + ) as call: + call.return_value = tag_keys.TagKey() + client.get_namespaced_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetNamespacedTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_key_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_key), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.CreateTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tag_key_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_key), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.UpdateTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_key_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_key), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.DeleteTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TagKeysAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tag_keys_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_keys), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_keys.ListTagKeysResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tag_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.ListTagKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_tag_key_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_keys.TagKey( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + purpose=tag_keys.Purpose.GCE_FIREWALL, + ) + ) + await client.get_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_namespaced_tag_key_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_keys.TagKey( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + purpose=tag_keys.Purpose.GCE_FIREWALL, + ) + ) + await client.get_namespaced_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetNamespacedTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tag_key_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.CreateTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_tag_key_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.UpdateTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tag_key_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_key), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.DeleteTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TagKeysClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_tag_keys_rest_bad_request(request_type=tag_keys.ListTagKeysRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_tag_keys(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.ListTagKeysRequest, + dict, + ], +) +def test_list_tag_keys_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_keys.ListTagKeysResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_keys.ListTagKeysResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tag_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagKeysPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_keys_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_list_tag_keys" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_list_tag_keys" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.ListTagKeysRequest.pb(tag_keys.ListTagKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_keys.ListTagKeysResponse.to_json( + tag_keys.ListTagKeysResponse() + ) + req.return_value.content = return_value + + request = tag_keys.ListTagKeysRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_keys.ListTagKeysResponse() + + client.list_tag_keys( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tag_key_rest_bad_request(request_type=tag_keys.GetTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagKeys/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_tag_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.GetTagKeyRequest, + dict, + ], +) +def test_get_tag_key_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagKeys/sample1"} + 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 = tag_keys.TagKey( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + purpose=tag_keys.Purpose.GCE_FIREWALL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_keys.TagKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_tag_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_keys.TagKey) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.short_name == "short_name_value" + assert response.namespaced_name == "namespaced_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.purpose == tag_keys.Purpose.GCE_FIREWALL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_tag_key" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_get_tag_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.GetTagKeyRequest.pb(tag_keys.GetTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_keys.TagKey.to_json(tag_keys.TagKey()) + req.return_value.content = return_value + + request = tag_keys.GetTagKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_keys.TagKey() + + client.get_tag_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_namespaced_tag_key_rest_bad_request( + request_type=tag_keys.GetNamespacedTagKeyRequest, +): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_namespaced_tag_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.GetNamespacedTagKeyRequest, + dict, + ], +) +def test_get_namespaced_tag_key_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_keys.TagKey( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + purpose=tag_keys.Purpose.GCE_FIREWALL, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_keys.TagKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_namespaced_tag_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_keys.TagKey) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.short_name == "short_name_value" + assert response.namespaced_name == "namespaced_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.purpose == tag_keys.Purpose.GCE_FIREWALL + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_namespaced_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_namespaced_tag_key" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_get_namespaced_tag_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.GetNamespacedTagKeyRequest.pb( + tag_keys.GetNamespacedTagKeyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_keys.TagKey.to_json(tag_keys.TagKey()) + req.return_value.content = return_value + + request = tag_keys.GetNamespacedTagKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_keys.TagKey() + + client.get_namespaced_tag_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_key_rest_bad_request(request_type=tag_keys.CreateTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_tag_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.CreateTagKeyRequest, + dict, + ], +) +def test_create_tag_key_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_key"] = { + "name": "name_value", + "parent": "parent_value", + "short_name": "short_name_value", + "namespaced_name": "namespaced_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "purpose": 1, + "purpose_data": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_keys.CreateTagKeyRequest.meta.fields["tag_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_key"][field])): + del request_init["tag_key"][field][i][subfield] + else: + del request_init["tag_key"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_tag_key(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagKeysRestInterceptor, "post_create_tag_key" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_create_tag_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.CreateTagKeyRequest.pb(tag_keys.CreateTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_keys.CreateTagKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tag_key_rest_bad_request(request_type=tag_keys.UpdateTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tag_key": {"name": "tagKeys/sample1"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_tag_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.UpdateTagKeyRequest, + dict, + ], +) +def test_update_tag_key_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tag_key": {"name": "tagKeys/sample1"}} + request_init["tag_key"] = { + "name": "tagKeys/sample1", + "parent": "parent_value", + "short_name": "short_name_value", + "namespaced_name": "namespaced_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "purpose": 1, + "purpose_data": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_keys.UpdateTagKeyRequest.meta.fields["tag_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_key"][field])): + del request_init["tag_key"][field][i][subfield] + else: + del request_init["tag_key"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_tag_key(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagKeysRestInterceptor, "post_update_tag_key" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_update_tag_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.UpdateTagKeyRequest.pb(tag_keys.UpdateTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_keys.UpdateTagKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tag_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_key_rest_bad_request(request_type=tag_keys.DeleteTagKeyRequest): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagKeys/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_tag_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_keys.DeleteTagKeyRequest, + dict, + ], +) +def test_delete_tag_key_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagKeys/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_tag_key(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_key_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagKeysRestInterceptor, "post_delete_tag_key" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_delete_tag_key" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_keys.DeleteTagKeyRequest.pb(tag_keys.DeleteTagKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_keys.DeleteTagKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagKeys/sample1"} + 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.TagKeysRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagKeysRestInterceptor(), + ) + client = TagKeysClient(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.TagKeysRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.TagKeysRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_keys_empty_call_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_keys), "__call__") as call: + client.list_tag_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.ListTagKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tag_key_empty_call_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_key), "__call__") as call: + client.get_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_namespaced_tag_key_empty_call_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_key), "__call__" + ) as call: + client.get_namespaced_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.GetNamespacedTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_key_empty_call_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_key), "__call__") as call: + client.create_tag_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.CreateTagKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tag_key_empty_call_rest(): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_key), "__call__") as call: + client.update_tag_key(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.UpdateTagKeyRequest() -def test_test_iam_permissions_rest_error(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagKeysGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_key_empty_call_rest(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagKeysClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_key), "__call__") as call: + client.delete_tag_key(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagKeysClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_keys.DeleteTagKeyRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagKeysClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.TagKeysGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TagKeysClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagKeysGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TagKeysClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagKeysGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.TagKeysGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagKeysGrpcTransport, - transports.TagKeysGrpcAsyncIOTransport, - transports.TagKeysRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = TagKeysClient.get_transport_class(transport_name)( + +def test_tag_keys_rest_lro_client(): + client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7858,23 +8152,6 @@ def test_tag_keys_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_tag_keys_rest_lro_client(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8265,76 +8542,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = TagKeysClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8362,7 +8569,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8417,7 +8624,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8464,7 +8671,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = TagKeysAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8480,22 +8687,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = TagKeysClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = TagKeysAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = TagKeysClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_values.py b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_values.py index 588bda204436..be94adfd2801 100644 --- a/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_values.py +++ b/packages/google-cloud-resource-manager/tests/unit/gapic/resourcemanager_v3/test_tag_values.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -48,16 +65,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import expr_pb2 # type: ignore -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.resourcemanager_v3.services.tag_values import ( TagValuesAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.resourcemanager_v3.types import tag_values +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1129,25 +1152,6 @@ def test_list_tag_values(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_tag_values_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_values), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_tag_values() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.ListTagValuesRequest() - - def test_list_tag_values_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1213,29 +1217,6 @@ def test_list_tag_values_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_tag_values_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tag_values), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_values.ListTagValuesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_tag_values() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.ListTagValuesRequest() - - @pytest.mark.asyncio async def test_list_tag_values_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1244,7 +1225,7 @@ async def test_list_tag_values_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1283,7 +1264,7 @@ async def test_list_tag_values_async( transport: str = "grpc_asyncio", request_type=tag_values.ListTagValuesRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1358,7 +1339,7 @@ def test_list_tag_values_flattened_error(): @pytest.mark.asyncio async def test_list_tag_values_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1387,7 +1368,7 @@ async def test_list_tag_values_flattened_async(): @pytest.mark.asyncio async def test_list_tag_values_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1494,7 +1475,7 @@ def test_list_tag_values_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_tag_values_async_pager(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1544,7 +1525,7 @@ async def test_list_tag_values_async_pager(): @pytest.mark.asyncio async def test_list_tag_values_async_pages(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1636,25 +1617,6 @@ def test_get_tag_value(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_tag_value), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetTagValueRequest() - - def test_get_tag_value_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1718,34 +1680,6 @@ def test_get_tag_value_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_tag_value_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_tag_value), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_values.TagValue( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - ) - ) - response = await client.get_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetTagValueRequest() - - @pytest.mark.asyncio async def test_get_tag_value_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1754,7 +1688,7 @@ async def test_get_tag_value_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1793,7 +1727,7 @@ async def test_get_tag_value_async( transport: str = "grpc_asyncio", request_type=tag_values.GetTagValueRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1869,7 +1803,7 @@ def test_get_tag_value_field_headers(): @pytest.mark.asyncio async def test_get_tag_value_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1937,7 +1871,7 @@ def test_get_tag_value_flattened_error(): @pytest.mark.asyncio async def test_get_tag_value_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1964,7 +1898,7 @@ async def test_get_tag_value_flattened_async(): @pytest.mark.asyncio async def test_get_tag_value_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2024,27 +1958,6 @@ def test_get_namespaced_tag_value(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_namespaced_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespaced_tag_value), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_namespaced_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetNamespacedTagValueRequest() - - def test_get_namespaced_tag_value_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2115,36 +2028,6 @@ def test_get_namespaced_tag_value_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_namespaced_tag_value_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_namespaced_tag_value), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tag_values.TagValue( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - ) - ) - response = await client.get_namespaced_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.GetNamespacedTagValueRequest() - - @pytest.mark.asyncio async def test_get_namespaced_tag_value_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2153,7 +2036,7 @@ async def test_get_namespaced_tag_value_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2193,7 +2076,7 @@ async def test_get_namespaced_tag_value_async( request_type=tag_values.GetNamespacedTagValueRequest, ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2282,7 +2165,7 @@ def test_get_namespaced_tag_value_flattened_error(): @pytest.mark.asyncio async def test_get_namespaced_tag_value_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2311,7 +2194,7 @@ async def test_get_namespaced_tag_value_flattened_async(): @pytest.mark.asyncio async def test_get_namespaced_tag_value_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2356,25 +2239,6 @@ def test_create_tag_value(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_value), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.CreateTagValueRequest() - - def test_create_tag_value_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2441,27 +2305,6 @@ def test_create_tag_value_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_tag_value_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_tag_value), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.CreateTagValueRequest() - - @pytest.mark.asyncio async def test_create_tag_value_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2470,7 +2313,7 @@ async def test_create_tag_value_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2514,7 +2357,7 @@ async def test_create_tag_value_async( transport: str = "grpc_asyncio", request_type=tag_values.CreateTagValueRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2586,7 +2429,7 @@ def test_create_tag_value_flattened_error(): @pytest.mark.asyncio async def test_create_tag_value_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2615,7 +2458,7 @@ async def test_create_tag_value_flattened_async(): @pytest.mark.asyncio async def test_create_tag_value_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2660,25 +2503,6 @@ def test_update_tag_value(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_tag_value), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.UpdateTagValueRequest() - - def test_update_tag_value_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2745,27 +2569,6 @@ def test_update_tag_value_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_tag_value_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_tag_value), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.UpdateTagValueRequest() - - @pytest.mark.asyncio async def test_update_tag_value_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2774,7 +2577,7 @@ async def test_update_tag_value_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2818,7 +2621,7 @@ async def test_update_tag_value_async( transport: str = "grpc_asyncio", request_type=tag_values.UpdateTagValueRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2881,7 +2684,7 @@ def test_update_tag_value_field_headers(): @pytest.mark.asyncio async def test_update_tag_value_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2956,7 +2759,7 @@ def test_update_tag_value_flattened_error(): @pytest.mark.asyncio async def test_update_tag_value_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2989,7 +2792,7 @@ async def test_update_tag_value_flattened_async(): @pytest.mark.asyncio async def test_update_tag_value_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3035,25 +2838,6 @@ def test_delete_tag_value(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_tag_value_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_value), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.DeleteTagValueRequest() - - def test_delete_tag_value_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3126,27 +2910,6 @@ def test_delete_tag_value_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_tag_value_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_tag_value), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_tag_value() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == tag_values.DeleteTagValueRequest() - - @pytest.mark.asyncio async def test_delete_tag_value_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3155,7 +2918,7 @@ async def test_delete_tag_value_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3199,7 +2962,7 @@ async def test_delete_tag_value_async( transport: str = "grpc_asyncio", request_type=tag_values.DeleteTagValueRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3262,7 +3025,7 @@ def test_delete_tag_value_field_headers(): @pytest.mark.asyncio async def test_delete_tag_value_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3332,7 +3095,7 @@ def test_delete_tag_value_flattened_error(): @pytest.mark.asyncio async def test_delete_tag_value_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3361,7 +3124,7 @@ async def test_delete_tag_value_flattened_async(): @pytest.mark.asyncio async def test_delete_tag_value_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3411,25 +3174,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3493,30 +3237,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3525,7 +3245,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3564,7 +3284,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3632,7 +3352,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3717,7 +3437,7 @@ def test_get_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3744,7 +3464,7 @@ async def test_get_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3794,25 +3514,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3876,30 +3577,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3908,7 +3585,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3947,7 +3624,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4015,7 +3692,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4101,7 +3778,7 @@ def test_set_iam_policy_flattened_error(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4128,7 +3805,7 @@ async def test_set_iam_policy_flattened_async(): @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4178,27 +3855,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4268,31 +3924,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4301,7 +3932,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4341,7 +3972,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4411,7 +4042,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4509,7 +4140,7 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4544,7 +4175,7 @@ async def test_test_iam_permissions_flattened_async(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4557,46 +4188,6 @@ async def test_test_iam_permissions_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - tag_values.ListTagValuesRequest, - dict, - ], -) -def test_list_tag_values_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_values.ListTagValuesResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_values.ListTagValuesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_tag_values(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTagValuesPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_tag_values_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4742,85 +4333,6 @@ def test_list_tag_values_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tag_values_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_list_tag_values" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_list_tag_values" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.ListTagValuesRequest.pb( - tag_values.ListTagValuesRequest() - ) - 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 = tag_values.ListTagValuesResponse.to_json( - tag_values.ListTagValuesResponse() - ) - - request = tag_values.ListTagValuesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_values.ListTagValuesResponse() - - client.list_tag_values( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tag_values_rest_bad_request( - transport: str = "rest", request_type=tag_values.ListTagValuesRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.list_tag_values(request) - - def test_list_tag_values_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4937,64 +4449,14 @@ def test_list_tag_values_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - tag_values.GetTagValueRequest, - dict, - ], -) -def test_get_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1"} - 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 = tag_values.TagValue( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_values.TagValue.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_tag_value(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_values.TagValue) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.short_name == "short_name_value" - assert response.namespaced_name == "namespaced_name_value" - assert response.description == "description_value" - assert response.etag == "etag_value" - - -def test_get_tag_value_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_tag_value_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -5104,81 +4566,6 @@ def test_get_tag_value_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_tag_value" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_get_tag_value" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.GetTagValueRequest.pb(tag_values.GetTagValueRequest()) - 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 = tag_values.TagValue.to_json(tag_values.TagValue()) - - request = tag_values.GetTagValueRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_values.TagValue() - - client.get_tag_value( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_tag_value_rest_bad_request( - transport: str = "rest", request_type=tag_values.GetTagValueRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1"} - 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_tag_value(request) - - def test_get_tag_value_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5234,62 +4621,6 @@ def test_get_tag_value_rest_flattened_error(transport: str = "rest"): ) -def test_get_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_values.GetNamespacedTagValueRequest, - dict, - ], -) -def test_get_namespaced_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - 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 = tag_values.TagValue( - name="name_value", - parent="parent_value", - short_name="short_name_value", - namespaced_name="namespaced_name_value", - description="description_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tag_values.TagValue.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_namespaced_tag_value(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tag_values.TagValue) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.short_name == "short_name_value" - assert response.namespaced_name == "namespaced_name_value" - assert response.description == "description_value" - assert response.etag == "etag_value" - - def test_get_namespaced_tag_value_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5425,83 +4756,6 @@ def test_get_namespaced_tag_value_rest_unset_required_fields(): assert set(unset_fields) == (set(("name",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_namespaced_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_namespaced_tag_value" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_get_namespaced_tag_value" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.GetNamespacedTagValueRequest.pb( - tag_values.GetNamespacedTagValueRequest() - ) - 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 = tag_values.TagValue.to_json(tag_values.TagValue()) - - request = tag_values.GetNamespacedTagValueRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tag_values.TagValue() - - client.get_namespaced_tag_value( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_namespaced_tag_value_rest_bad_request( - transport: str = "rest", request_type=tag_values.GetNamespacedTagValueRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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_namespaced_tag_value(request) - - def test_get_namespaced_tag_value_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5557,136 +4811,18 @@ def test_get_namespaced_tag_value_rest_flattened_error(transport: str = "rest"): ) -def test_get_namespaced_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_tag_value_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - tag_values.CreateTagValueRequest, - dict, - ], -) -def test_create_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["tag_value"] = { - "name": "name_value", - "parent": "parent_value", - "short_name": "short_name_value", - "namespaced_name": "namespaced_name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = tag_values.CreateTagValueRequest.meta.fields["tag_value"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_value"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_value"][field])): - del request_init["tag_value"][field][i][subfield] - else: - del request_init["tag_value"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_tag_value_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.create_tag_value in client._transport._wrapped_methods @@ -5795,87 +4931,6 @@ def test_create_tag_value_rest_unset_required_fields(): assert set(unset_fields) == (set(("validateOnly",)) & set(("tagValue",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagValuesRestInterceptor, "post_create_tag_value" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_create_tag_value" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.CreateTagValueRequest.pb( - tag_values.CreateTagValueRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_values.CreateTagValueRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_tag_value( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_tag_value_rest_bad_request( - transport: str = "rest", request_type=tag_values.CreateTagValueRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - 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.create_tag_value(request) - - def test_create_tag_value_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5929,151 +4984,33 @@ def test_create_tag_value_rest_flattened_error(transport: str = "rest"): ) -def test_create_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_update_tag_value_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - tag_values.UpdateTagValueRequest, - dict, - ], -) -def test_update_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = {"tag_value": {"name": "tagValues/sample1"}} - request_init["tag_value"] = { - "name": "tagValues/sample1", - "parent": "parent_value", - "short_name": "short_name_value", - "namespaced_name": "namespaced_name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Ensure method has been cached + assert client._transport.update_tag_value in client._transport._wrapped_methods - # Determine if the message type is proto-plus or protobuf - test_field = tag_values.UpdateTagValueRequest.meta.fields["tag_value"] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_tag_value + ] = mock_rpc - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["tag_value"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["tag_value"][field])): - del request_init["tag_value"][field][i][subfield] - else: - del request_init["tag_value"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_tag_value_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_tag_value in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_tag_value - ] = mock_rpc - - request = {} - client.update_tag_value(request) + request = {} + client.update_tag_value(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6180,87 +5117,6 @@ def test_update_tag_value_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagValuesRestInterceptor, "post_update_tag_value" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_update_tag_value" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.UpdateTagValueRequest.pb( - tag_values.UpdateTagValueRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_values.UpdateTagValueRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_tag_value( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_tag_value_rest_bad_request( - transport: str = "rest", request_type=tag_values.UpdateTagValueRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"tag_value": {"name": "tagValues/sample1"}} - 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_tag_value(request) - - def test_update_tag_value_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6316,47 +5172,6 @@ def test_update_tag_value_rest_flattened_error(transport: str = "rest"): ) -def test_update_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - tag_values.DeleteTagValueRequest, - dict, - ], -) -def test_delete_tag_value_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_tag_value(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_tag_value_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6494,97 +5309,16 @@ def test_delete_tag_value_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_tag_value_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( +def test_delete_tag_value_rest_flattened(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + transport="rest", ) - client = TagValuesClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.TagValuesRestInterceptor, "post_delete_tag_value" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_delete_tag_value" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = tag_values.DeleteTagValueRequest.pb( - tag_values.DeleteTagValueRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = tag_values.DeleteTagValueRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_tag_value( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_tag_value_rest_bad_request( - transport: str = "rest", request_type=tag_values.DeleteTagValueRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "tagValues/sample1"} - 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.delete_tag_value(request) - - -def test_delete_tag_value_rest_flattened(): - client = TagValuesClient( - 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 = operations_pb2.Operation(name="operations/spam") + # 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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"name": "tagValues/sample1"} @@ -6628,52 +5362,6 @@ def test_delete_tag_value_rest_flattened_error(transport: str = "rest"): ) -def test_delete_tag_value_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6792,81 +5480,6 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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_iam_policy(request) - - def test_get_iam_policy_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6921,52 +5534,6 @@ def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_get_iam_policy_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_set_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7093,94 +5660,19 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( +def test_set_iam_policy_rest_flattened(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + transport="rest", ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) + # 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 = policy_pb2.Policy() - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = TagValuesClient( - 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 = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {"resource": "tagValues/sample1"} + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "tagValues/sample1"} # get truthy value for each flattened field mock_args = dict( @@ -7222,50 +5714,6 @@ def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): ) -def test_set_iam_policy_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7400,83 +5848,6 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.TagValuesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), - ) - client = TagValuesClient(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.TagValuesRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.TagValuesRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "tagValues/sample1"} - 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.test_iam_permissions(request) - - def test_test_iam_permissions_rest_flattened(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7517,132 +5888,2061 @@ def test_test_iam_permissions_rest_flattened(): ) -def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = TagValuesClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagValuesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TagValuesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TagValuesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TagValuesClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TagValuesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TagValuesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TagValuesGrpcTransport, + transports.TagValuesGrpcAsyncIOTransport, + transports.TagValuesRestTransport, + ], +) +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_transport_kind_grpc(): + transport = TagValuesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_values_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_values), "__call__") as call: + call.return_value = tag_values.ListTagValuesResponse() + client.list_tag_values(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.ListTagValuesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tag_value_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_value), "__call__") as call: + call.return_value = tag_values.TagValue() + client.get_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_namespaced_tag_value_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_value), "__call__" + ) as call: + call.return_value = tag_values.TagValue() + client.get_namespaced_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetNamespacedTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_value_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_value), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.CreateTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tag_value_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_value), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.UpdateTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_value_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_value), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.DeleteTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TagValuesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tag_values_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_values), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_values.ListTagValuesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tag_values(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.ListTagValuesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_tag_value_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_value), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_values.TagValue( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + ) + ) + await client.get_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_namespaced_tag_value_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_value), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tag_values.TagValue( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + ) + ) + await client.get_namespaced_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetNamespacedTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tag_value_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_value), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.CreateTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_tag_value_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_value), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.UpdateTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tag_value_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_value), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.DeleteTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TagValuesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_tag_values_rest_bad_request(request_type=tag_values.ListTagValuesRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_tag_values(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.ListTagValuesRequest, + dict, + ], +) +def test_list_tag_values_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_values.ListTagValuesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_values.ListTagValuesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tag_values(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTagValuesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tag_values_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_list_tag_values" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_list_tag_values" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.ListTagValuesRequest.pb( + tag_values.ListTagValuesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_values.ListTagValuesResponse.to_json( + tag_values.ListTagValuesResponse() + ) + req.return_value.content = return_value + + request = tag_values.ListTagValuesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_values.ListTagValuesResponse() + + client.list_tag_values( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_tag_value_rest_bad_request(request_type=tag_values.GetTagValueRequest): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_tag_value(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.GetTagValueRequest, + dict, + ], +) +def test_get_tag_value_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1"} + 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 = tag_values.TagValue( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_values.TagValue.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_tag_value(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_values.TagValue) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.short_name == "short_name_value" + assert response.namespaced_name == "namespaced_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_tag_value" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_get_tag_value" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.GetTagValueRequest.pb(tag_values.GetTagValueRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_values.TagValue.to_json(tag_values.TagValue()) + req.return_value.content = return_value + + request = tag_values.GetTagValueRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_values.TagValue() + + client.get_tag_value( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_namespaced_tag_value_rest_bad_request( + request_type=tag_values.GetNamespacedTagValueRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_namespaced_tag_value(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.GetNamespacedTagValueRequest, + dict, + ], +) +def test_get_namespaced_tag_value_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = tag_values.TagValue( + name="name_value", + parent="parent_value", + short_name="short_name_value", + namespaced_name="namespaced_name_value", + description="description_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tag_values.TagValue.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_namespaced_tag_value(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tag_values.TagValue) + assert response.name == "name_value" + assert response.parent == "parent_value" + assert response.short_name == "short_name_value" + assert response.namespaced_name == "namespaced_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_namespaced_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_namespaced_tag_value" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_get_namespaced_tag_value" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.GetNamespacedTagValueRequest.pb( + tag_values.GetNamespacedTagValueRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = tag_values.TagValue.to_json(tag_values.TagValue()) + req.return_value.content = return_value + + request = tag_values.GetNamespacedTagValueRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tag_values.TagValue() + + client.get_namespaced_tag_value( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_tag_value_rest_bad_request( + request_type=tag_values.CreateTagValueRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_tag_value(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.CreateTagValueRequest, + dict, + ], +) +def test_create_tag_value_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["tag_value"] = { + "name": "name_value", + "parent": "parent_value", + "short_name": "short_name_value", + "namespaced_name": "namespaced_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_values.CreateTagValueRequest.meta.fields["tag_value"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_value"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_value"][field])): + del request_init["tag_value"][field][i][subfield] + else: + del request_init["tag_value"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_tag_value(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagValuesRestInterceptor, "post_create_tag_value" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_create_tag_value" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.CreateTagValueRequest.pb( + tag_values.CreateTagValueRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_values.CreateTagValueRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_tag_value( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_tag_value_rest_bad_request( + request_type=tag_values.UpdateTagValueRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"tag_value": {"name": "tagValues/sample1"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_tag_value(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.UpdateTagValueRequest, + dict, + ], +) +def test_update_tag_value_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"tag_value": {"name": "tagValues/sample1"}} + request_init["tag_value"] = { + "name": "tagValues/sample1", + "parent": "parent_value", + "short_name": "short_name_value", + "namespaced_name": "namespaced_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = tag_values.UpdateTagValueRequest.meta.fields["tag_value"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tag_value"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tag_value"][field])): + del request_init["tag_value"][field][i][subfield] + else: + del request_init["tag_value"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_tag_value(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagValuesRestInterceptor, "post_update_tag_value" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_update_tag_value" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.UpdateTagValueRequest.pb( + tag_values.UpdateTagValueRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_values.UpdateTagValueRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_tag_value( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_tag_value_rest_bad_request( + request_type=tag_values.DeleteTagValueRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_tag_value(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tag_values.DeleteTagValueRequest, + dict, + ], +) +def test_delete_tag_value_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "tagValues/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_tag_value(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tag_value_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.TagValuesRestInterceptor, "post_delete_tag_value" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_delete_tag_value" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = tag_values.DeleteTagValueRequest.pb( + tag_values.DeleteTagValueRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = tag_values.DeleteTagValueRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_tag_value( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "tagValues/sample1"} + 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.TagValuesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TagValuesRestInterceptor(), + ) + client = TagValuesClient(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.TagValuesRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.TagValuesRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "operations/sample1"}, request) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "operations/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tag_values_empty_call_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tag_values), "__call__") as call: + client.list_tag_values(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.ListTagValuesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tag_value_empty_call_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tag_value), "__call__") as call: + client.get_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_namespaced_tag_value_empty_call_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_namespaced_tag_value), "__call__" + ) as call: + client.get_namespaced_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.GetNamespacedTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tag_value_empty_call_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tag_value), "__call__") as call: + client.create_tag_value(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.CreateTagValueRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tag_value_empty_call_rest(): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource="resource_value", - permissions=["permissions_value"], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tag_value), "__call__") as call: + client.update_tag_value(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.UpdateTagValueRequest() -def test_test_iam_permissions_rest_error(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TagValuesGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tag_value_empty_call_rest(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TagValuesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tag_value), "__call__") as call: + client.delete_tag_value(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagValuesClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tag_values.DeleteTagValueRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TagValuesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.TagValuesGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = TagValuesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagValuesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TagValuesClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TagValuesGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.TagValuesGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TagValuesGrpcTransport, - transports.TagValuesGrpcAsyncIOTransport, - transports.TagValuesRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = TagValuesClient.get_transport_class(transport_name)( + +def test_tag_values_rest_lro_client(): + client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7897,23 +8197,6 @@ def test_tag_values_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_tag_values_rest_lro_client(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8304,76 +8587,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({"name": "operations/sample1"}, request) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "operations/sample1"} - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - def test_get_operation(transport: str = "grpc"): client = TagValuesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8401,7 +8614,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8456,7 +8669,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8503,7 +8716,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = TagValuesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8519,22 +8732,41 @@ async def test_get_operation_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = TagValuesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = TagValuesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = TagValuesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/README.rst b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/README.rst new file mode 100644 index 000000000000..9a8431279b6e --- /dev/null +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ResourceSettingsServiceTransport` is the ABC for all transports. +- public child `ResourceSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ResourceSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseResourceSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ResourceSettingsServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/grpc_asyncio.py b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/grpc_asyncio.py index 8b6cc6143243..ac5e0cc0276c 100644 --- a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -242,6 +243,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -361,7 +365,7 @@ def update_setting( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_settings: gapic_v1.method_async.wrap_method( + self.list_settings: self._wrap_method( self.list_settings, default_retry=retries.AsyncRetry( initial=1.0, @@ -376,7 +380,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.get_setting: gapic_v1.method_async.wrap_method( + self.get_setting: self._wrap_method( self.get_setting, default_retry=retries.AsyncRetry( initial=1.0, @@ -391,7 +395,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.update_setting: gapic_v1.method_async.wrap_method( + self.update_setting: self._wrap_method( self.update_setting, default_retry=retries.AsyncRetry( initial=1.0, @@ -408,8 +412,17 @@ def _prep_wrapped_messages(self, client_info): ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + __all__ = ("ResourceSettingsServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest.py b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest.py index 6ec6f335405c..f68b3667fb6c 100644 --- a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest.py +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest.py @@ -16,31 +16,28 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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 +from google.cloud.resourcesettings_v1.types import resource_settings + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseResourceSettingsServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.cloud.resourcesettings_v1.types import resource_settings - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ResourceSettingsServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -170,8 +167,8 @@ class ResourceSettingsServiceRestStub: _interceptor: ResourceSettingsServiceRestInterceptor -class ResourceSettingsServiceRestTransport(ResourceSettingsServiceTransport): - """REST backend transport for ResourceSettingsService. +class ResourceSettingsServiceRestTransport(_BaseResourceSettingsServiceRestTransport): + """REST backend synchronous transport for ResourceSettingsService. An interface to interact with resource settings and setting values throughout the resource hierarchy. @@ -196,7 +193,6 @@ class ResourceSettingsServiceRestTransport(ResourceSettingsServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -250,21 +246,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -275,19 +262,34 @@ def __init__( self._interceptor = interceptor or ResourceSettingsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetSetting(ResourceSettingsServiceRestStub): + class _GetSetting( + _BaseResourceSettingsServiceRestTransport._BaseGetSetting, + ResourceSettingsServiceRestStub, + ): def __hash__(self): - return hash("GetSetting") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ResourceSettingsServiceRestTransport.GetSetting") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -313,46 +315,27 @@ def __call__( The schema for settings. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{name=organizations/*/settings/*}", - }, - { - "method": "get", - "uri": "/v1/{name=folders/*/settings/*}", - }, - { - "method": "get", - "uri": "/v1/{name=projects/*/settings/*}", - }, - ] + http_options = ( + _BaseResourceSettingsServiceRestTransport._BaseGetSetting._get_http_options() + ) request, metadata = self._interceptor.pre_get_setting(request, metadata) - pb_request = resource_settings.GetSettingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseResourceSettingsServiceRestTransport._BaseGetSetting._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseResourceSettingsServiceRestTransport._BaseGetSetting._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ResourceSettingsServiceRestTransport._GetSetting._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -368,19 +351,34 @@ def __call__( resp = self._interceptor.post_get_setting(resp) return resp - class _ListSettings(ResourceSettingsServiceRestStub): + class _ListSettings( + _BaseResourceSettingsServiceRestTransport._BaseListSettings, + ResourceSettingsServiceRestStub, + ): def __hash__(self): - return hash("ListSettings") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ResourceSettingsServiceRestTransport.ListSettings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -406,46 +404,27 @@ def __call__( The response from ListSettings. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=organizations/*}/settings", - }, - { - "method": "get", - "uri": "/v1/{parent=folders/*}/settings", - }, - { - "method": "get", - "uri": "/v1/{parent=projects/*}/settings", - }, - ] + http_options = ( + _BaseResourceSettingsServiceRestTransport._BaseListSettings._get_http_options() + ) request, metadata = self._interceptor.pre_list_settings(request, metadata) - pb_request = resource_settings.ListSettingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseResourceSettingsServiceRestTransport._BaseListSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseResourceSettingsServiceRestTransport._BaseListSettings._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ResourceSettingsServiceRestTransport._ListSettings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -461,19 +440,35 @@ def __call__( resp = self._interceptor.post_list_settings(resp) return resp - class _UpdateSetting(ResourceSettingsServiceRestStub): + class _UpdateSetting( + _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting, + ResourceSettingsServiceRestStub, + ): def __hash__(self): - return hash("UpdateSetting") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ResourceSettingsServiceRestTransport.UpdateSetting") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -499,55 +494,34 @@ def __call__( The schema for settings. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v1/{setting.name=organizations/*/settings/*}", - "body": "setting", - }, - { - "method": "patch", - "uri": "/v1/{setting.name=folders/*/settings/*}", - "body": "setting", - }, - { - "method": "patch", - "uri": "/v1/{setting.name=projects/*/settings/*}", - "body": "setting", - }, - ] + http_options = ( + _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting._get_http_options() + ) request, metadata = self._interceptor.pre_update_setting(request, metadata) - pb_request = resource_settings.UpdateSettingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ResourceSettingsServiceRestTransport._UpdateSetting._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest_base.py b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..83fda2c79503 --- /dev/null +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/services/resource_settings_service/transports/rest_base.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.resourcesettings_v1.types import resource_settings + +from .base import DEFAULT_CLIENT_INFO, ResourceSettingsServiceTransport + + +class _BaseResourceSettingsServiceRestTransport(ResourceSettingsServiceTransport): + """Base REST backend transport for ResourceSettingsService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "resourcesettings.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'resourcesettings.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetSetting: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/settings/*}", + }, + { + "method": "get", + "uri": "/v1/{name=folders/*/settings/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/settings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = resource_settings.GetSettingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseResourceSettingsServiceRestTransport._BaseGetSetting._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSettings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*}/settings", + }, + { + "method": "get", + "uri": "/v1/{parent=folders/*}/settings", + }, + { + "method": "get", + "uri": "/v1/{parent=projects/*}/settings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = resource_settings.ListSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseResourceSettingsServiceRestTransport._BaseListSettings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSetting: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{setting.name=organizations/*/settings/*}", + "body": "setting", + }, + { + "method": "patch", + "uri": "/v1/{setting.name=folders/*/settings/*}", + "body": "setting", + }, + { + "method": "patch", + "uri": "/v1/{setting.name=projects/*/settings/*}", + "body": "setting", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = resource_settings.UpdateSettingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseResourceSettingsServiceRestTransport._BaseUpdateSetting._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseResourceSettingsServiceRestTransport",) diff --git a/packages/google-cloud-resource-settings/setup.py b/packages/google-cloud-resource-settings/setup.py index 2cd55eb6d197..518eb6a070f3 100644 --- a/packages/google-cloud-resource-settings/setup.py +++ b/packages/google-cloud-resource-settings/setup.py @@ -48,6 +48,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -90,6 +91,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-resource-settings/tests/unit/gapic/resourcesettings_v1/test_resource_settings_service.py b/packages/google-cloud-resource-settings/tests/unit/gapic/resourcesettings_v1/test_resource_settings_service.py index 83a05a6001e3..6bc35a9e0ec3 100644 --- a/packages/google-cloud-resource-settings/tests/unit/gapic/resourcesettings_v1/test_resource_settings_service.py +++ b/packages/google-cloud-resource-settings/tests/unit/gapic/resourcesettings_v1/test_resource_settings_service.py @@ -22,18 +22,11 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math -from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -import google.auth -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.oauth2 import service_account +from google.api_core import api_core_version from google.protobuf import json_format import grpc from grpc.experimental import aio @@ -43,6 +36,22 @@ from requests import PreparedRequest, Request, Response from requests.sessions import Session +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + from google.cloud.resourcesettings_v1.services.resource_settings_service import ( ResourceSettingsServiceAsyncClient, ResourceSettingsServiceClient, @@ -52,10 +61,24 @@ from google.cloud.resourcesettings_v1.types import resource_settings +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1225,25 +1248,6 @@ def test_list_settings(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_settings), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.ListSettingsRequest() - - def test_list_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1309,29 +1313,6 @@ def test_list_settings_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_settings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_settings), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource_settings.ListSettingsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.ListSettingsRequest() - - @pytest.mark.asyncio async def test_list_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1340,7 +1321,7 @@ async def test_list_settings_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1379,7 +1360,7 @@ async def test_list_settings_async( transport: str = "grpc_asyncio", request_type=resource_settings.ListSettingsRequest ): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1445,7 +1426,7 @@ def test_list_settings_field_headers(): @pytest.mark.asyncio async def test_list_settings_field_headers_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1515,7 +1496,7 @@ def test_list_settings_flattened_error(): @pytest.mark.asyncio async def test_list_settings_flattened_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1544,7 +1525,7 @@ async def test_list_settings_flattened_async(): @pytest.mark.asyncio async def test_list_settings_flattened_error_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1654,7 +1635,7 @@ def test_list_settings_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_settings_async_pager(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1704,7 +1685,7 @@ async def test_list_settings_async_pager(): @pytest.mark.asyncio async def test_list_settings_async_pages(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1788,25 +1769,6 @@ def test_get_setting(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_setting_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_setting), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_setting() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.GetSettingRequest() - - def test_get_setting_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1870,30 +1832,6 @@ def test_get_setting_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_setting_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_setting), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource_settings.Setting( - name="name_value", - etag="etag_value", - ) - ) - response = await client.get_setting() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.GetSettingRequest() - - @pytest.mark.asyncio async def test_get_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1902,7 +1840,7 @@ async def test_get_setting_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1941,7 +1879,7 @@ async def test_get_setting_async( transport: str = "grpc_asyncio", request_type=resource_settings.GetSettingRequest ): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2009,7 +1947,7 @@ def test_get_setting_field_headers(): @pytest.mark.asyncio async def test_get_setting_field_headers_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2079,7 +2017,7 @@ def test_get_setting_flattened_error(): @pytest.mark.asyncio async def test_get_setting_flattened_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2108,7 +2046,7 @@ async def test_get_setting_flattened_async(): @pytest.mark.asyncio async def test_get_setting_flattened_error_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2158,25 +2096,6 @@ def test_update_setting(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_update_setting_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_setting), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_setting() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.UpdateSettingRequest() - - def test_update_setting_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2236,30 +2155,6 @@ def test_update_setting_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_setting_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_setting), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resource_settings.Setting( - name="name_value", - etag="etag_value", - ) - ) - response = await client.update_setting() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == resource_settings.UpdateSettingRequest() - - @pytest.mark.asyncio async def test_update_setting_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2268,7 +2163,7 @@ async def test_update_setting_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2307,7 +2202,7 @@ async def test_update_setting_async( transport: str = "grpc_asyncio", request_type=resource_settings.UpdateSettingRequest ): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2375,7 +2270,7 @@ def test_update_setting_field_headers(): @pytest.mark.asyncio async def test_update_setting_field_headers_async(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2404,46 +2299,6 @@ async def test_update_setting_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - resource_settings.ListSettingsRequest, - dict, - ], -) -def test_list_settings_rest(request_type): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1"} - 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 = resource_settings.ListSettingsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_settings.ListSettingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSettingsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2580,87 +2435,6 @@ def test_list_settings_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_settings_rest_interceptors(null_interceptor): - transport = transports.ResourceSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ResourceSettingsServiceRestInterceptor(), - ) - client = ResourceSettingsServiceClient(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.ResourceSettingsServiceRestInterceptor, "post_list_settings" - ) as post, mock.patch.object( - transports.ResourceSettingsServiceRestInterceptor, "pre_list_settings" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = resource_settings.ListSettingsRequest.pb( - resource_settings.ListSettingsRequest() - ) - 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 = resource_settings.ListSettingsResponse.to_json( - resource_settings.ListSettingsResponse() - ) - - request = resource_settings.ListSettingsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_settings.ListSettingsResponse() - - client.list_settings( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_settings_rest_bad_request( - transport: str = "rest", request_type=resource_settings.ListSettingsRequest -): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1"} - 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.list_settings(request) - - def test_list_settings_rest_flattened(): client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2779,48 +2553,6 @@ def test_list_settings_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - resource_settings.GetSettingRequest, - dict, - ], -) -def test_get_setting_rest(request_type): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1/settings/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 = resource_settings.Setting( - name="name_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_settings.Setting.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_setting(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_settings.Setting) - assert response.name == "name_value" - assert response.etag == "etag_value" - - def test_get_setting_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2942,87 +2674,6 @@ def test_get_setting_rest_unset_required_fields(): assert set(unset_fields) == (set(("view",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_setting_rest_interceptors(null_interceptor): - transport = transports.ResourceSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ResourceSettingsServiceRestInterceptor(), - ) - client = ResourceSettingsServiceClient(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.ResourceSettingsServiceRestInterceptor, "post_get_setting" - ) as post, mock.patch.object( - transports.ResourceSettingsServiceRestInterceptor, "pre_get_setting" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = resource_settings.GetSettingRequest.pb( - resource_settings.GetSettingRequest() - ) - 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 = resource_settings.Setting.to_json( - resource_settings.Setting() - ) - - request = resource_settings.GetSettingRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resource_settings.Setting() - - client.get_setting( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_setting_rest_bad_request( - transport: str = "rest", request_type=resource_settings.GetSettingRequest -): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "organizations/sample1/settings/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.get_setting(request) - - def test_get_setting_rest_flattened(): client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3078,139 +2729,6 @@ def test_get_setting_rest_flattened_error(transport: str = "rest"): ) -def test_get_setting_rest_error(): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - resource_settings.UpdateSettingRequest, - dict, - ], -) -def test_update_setting_rest(request_type): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"setting": {"name": "organizations/sample1/settings/sample2"}} - request_init["setting"] = { - "name": "organizations/sample1/settings/sample2", - "metadata": { - "display_name": "display_name_value", - "description": "description_value", - "read_only": True, - "data_type": 1, - "default_value": { - "boolean_value": True, - "string_value": "string_value_value", - "string_set_value": {"values": ["values_value1", "values_value2"]}, - "enum_value": {"value": "value_value"}, - }, - }, - "local_value": {}, - "effective_value": {}, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = resource_settings.UpdateSettingRequest.meta.fields["setting"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["setting"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["setting"][field])): - del request_init["setting"][field][i][subfield] - else: - del request_init["setting"][field][subfield] - 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 = resource_settings.Setting( - name="name_value", - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resource_settings.Setting.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_setting(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resource_settings.Setting) - assert response.name == "name_value" - assert response.etag == "etag_value" - - def test_update_setting_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3273,57 +2791,720 @@ def test_update_setting_rest_required_fields( ).update_setting._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone + # verify required fields with non-default values are left alone + + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_settings.Setting() + # 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 + + # Convert return value to protobuf type + return_value = resource_settings.Setting.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_setting(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_setting_rest_unset_required_fields(): + transport = transports.ResourceSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("setting",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ResourceSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ResourceSettingsServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ResourceSettingsServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ResourceSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ResourceSettingsServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ResourceSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ResourceSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ResourceSettingsServiceGrpcTransport, + transports.ResourceSettingsServiceGrpcAsyncIOTransport, + transports.ResourceSettingsServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ResourceSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_settings_empty_call_grpc(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_settings), "__call__") as call: + call.return_value = resource_settings.ListSettingsResponse() + client.list_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.ListSettingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_setting_empty_call_grpc(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_setting), "__call__") as call: + call.return_value = resource_settings.Setting() + client.get_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.GetSettingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_setting_empty_call_grpc(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_setting), "__call__") as call: + call.return_value = resource_settings.Setting() + client.update_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.UpdateSettingRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ResourceSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ResourceSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_settings_empty_call_grpc_asyncio(): + client = ResourceSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_settings.ListSettingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.ListSettingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_setting_empty_call_grpc_asyncio(): + client = ResourceSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_setting), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_settings.Setting( + name="name_value", + etag="etag_value", + ) + ) + await client.get_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.GetSettingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_setting_empty_call_grpc_asyncio(): + client = ResourceSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_setting), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_settings.Setting( + name="name_value", + etag="etag_value", + ) + ) + await client.update_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.UpdateSettingRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ResourceSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_settings_rest_bad_request( + request_type=resource_settings.ListSettingsRequest, +): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_settings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + resource_settings.ListSettingsRequest, + dict, + ], +) +def test_list_settings_rest_call_success(request_type): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + 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 = resource_settings.ListSettingsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_settings.ListSettingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSettingsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_settings_rest_interceptors(null_interceptor): + transport = transports.ResourceSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ResourceSettingsServiceRestInterceptor(), + ) + client = ResourceSettingsServiceClient(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.ResourceSettingsServiceRestInterceptor, "post_list_settings" + ) as post, mock.patch.object( + transports.ResourceSettingsServiceRestInterceptor, "pre_list_settings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = resource_settings.ListSettingsRequest.pb( + resource_settings.ListSettingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resource_settings.ListSettingsResponse.to_json( + resource_settings.ListSettingsResponse() + ) + req.return_value.content = return_value + + request = resource_settings.ListSettingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_settings.ListSettingsResponse() + + client.list_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_setting_rest_bad_request(request_type=resource_settings.GetSettingRequest): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/settings/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_setting(request) + + +@pytest.mark.parametrize( + "request_type", + [ + resource_settings.GetSettingRequest, + dict, + ], +) +def test_get_setting_rest_call_success(request_type): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/settings/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 = resource_settings.Setting( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resource_settings.Setting.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_settings.Setting) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_setting_rest_interceptors(null_interceptor): + transport = transports.ResourceSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ResourceSettingsServiceRestInterceptor(), + ) + client = ResourceSettingsServiceClient(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.ResourceSettingsServiceRestInterceptor, "post_get_setting" + ) as post, mock.patch.object( + transports.ResourceSettingsServiceRestInterceptor, "pre_get_setting" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = resource_settings.GetSettingRequest.pb( + resource_settings.GetSettingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resource_settings.Setting.to_json(resource_settings.Setting()) + req.return_value.content = return_value + + request = resource_settings.GetSettingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_settings.Setting() + + client.get_setting( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_setting_rest_bad_request( + request_type=resource_settings.UpdateSettingRequest, +): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"setting": {"name": "organizations/sample1/settings/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_setting(request) + + +@pytest.mark.parametrize( + "request_type", + [ + resource_settings.UpdateSettingRequest, + dict, + ], +) +def test_update_setting_rest_call_success(request_type): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"setting": {"name": "organizations/sample1/settings/sample2"}} + request_init["setting"] = { + "name": "organizations/sample1/settings/sample2", + "metadata": { + "display_name": "display_name_value", + "description": "description_value", + "read_only": True, + "data_type": 1, + "default_value": { + "boolean_value": True, + "string_value": "string_value_value", + "string_set_value": {"values": ["values_value1", "values_value2"]}, + "enum_value": {"value": "value_value"}, + }, + }, + "local_value": {}, + "effective_value": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = resource_settings.UpdateSettingRequest.meta.fields["setting"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields - # Designate an appropriate value for the returned response. - return_value = resource_settings.Setting() - # 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 + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - response_value = Response() - response_value.status_code = 200 + subfields_not_in_runtime = [] - # Convert return value to protobuf type - return_value = resource_settings.Setting.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["setting"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - response = client.update_setting(request) + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["setting"][field])): + del request_init["setting"][field][i][subfield] + else: + del request_init["setting"][field][subfield] + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = resource_settings.Setting( + name="name_value", + etag="etag_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_update_setting_rest_unset_required_fields(): - transport = transports.ResourceSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = resource_settings.Setting.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_setting(request) - unset_fields = transport.update_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("setting",))) + # Establish that the response is the type that we expect. + assert isinstance(response, resource_settings.Setting) + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -3335,6 +3516,7 @@ def test_update_setting_rest_interceptors(null_interceptor): else transports.ResourceSettingsServiceRestInterceptor(), ) client = ResourceSettingsServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -3356,12 +3538,10 @@ def test_update_setting_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resource_settings.Setting.to_json( - resource_settings.Setting() - ) + return_value = resource_settings.Setting.to_json(resource_settings.Setting()) + req.return_value.content = return_value request = resource_settings.UpdateSettingRequest() metadata = [ @@ -3383,140 +3563,71 @@ def test_update_setting_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_setting_rest_bad_request( - transport: str = "rest", request_type=resource_settings.UpdateSettingRequest -): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"setting": {"name": "organizations/sample1/settings/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.update_setting(request) - - -def test_update_setting_rest_error(): +def test_initialize_client_w_rest(): client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_settings_empty_call_rest(): + client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ResourceSettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_settings), "__call__") as call: + client.list_settings(request=None) - # It is an error to provide an api_key and a transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ResourceSettingsServiceClient( - client_options=options, - transport=transport, - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.ListSettingsRequest() - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ResourceSettingsServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_setting_empty_call_rest(): + client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ResourceSettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_setting), "__call__") as call: + client.get_setting(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ResourceSettingsServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.GetSettingRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ResourceSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.ResourceSettingsServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_setting_empty_call_rest(): + client = ResourceSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ResourceSettingsServiceGrpcTransport, - transports.ResourceSettingsServiceGrpcAsyncIOTransport, - transports.ResourceSettingsServiceRestTransport, - ], -) -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() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_setting), "__call__") as call: + client.update_setting(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = resource_settings.UpdateSettingRequest() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ResourceSettingsServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name + assert args[0] == request_msg def test_transport_grpc_default(): @@ -4103,36 +4214,41 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_transport_close_grpc(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_transport_close_grpc_asyncio(): client = ResourceSettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" + type(getattr(client.transport, "_grpc_channel")), "close" ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ResourceSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() +def test_transport_close_rest(): + client = ResourceSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/google/cloud/retail/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail/gapic_version.py index 8b80cf328714..558c8aab67c5 100644 --- a/packages/google-cloud-retail/google/cloud/retail/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py index 8b80cf328714..558c8aab67c5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/async_client.py index 02b773295420..38c074203a1d 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/async_client.py @@ -403,11 +403,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -460,11 +456,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/client.py index cd921dba6458..54893c954689 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/README.rst new file mode 100644 index 000000000000..cf1d5125ad04 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AnalyticsServiceTransport` is the ABC for all transports. +- public child `AnalyticsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AnalyticsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAnalyticsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AnalyticsServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/base.py index 03f962a8bd79..e3db6ee87559 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/base.py @@ -145,6 +145,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/grpc_asyncio.py index 31c81114c2af..4b704d96e0cf 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -295,7 +299,7 @@ def export_analytics_metrics( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.export_analytics_metrics: gapic_v1.method_async.wrap_method( + self.export_analytics_metrics: self._wrap_method( self.export_analytics_metrics, default_retry=retries.AsyncRetry( initial=0.1, @@ -310,11 +314,30 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest.py index 4b4609d528ac..da5ba8b2989f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2.types import export_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAnalyticsServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2.types import export_config - -from .base import AnalyticsServiceTransport -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, @@ -163,8 +153,8 @@ class AnalyticsServiceRestStub: _interceptor: AnalyticsServiceRestInterceptor -class AnalyticsServiceRestTransport(AnalyticsServiceTransport): - """REST backend transport for AnalyticsService. +class AnalyticsServiceRestTransport(_BaseAnalyticsServiceRestTransport): + """REST backend synchronous transport for AnalyticsService. Service for managing & accessing retail search business metric. Retail recommendation business metric is currently not @@ -175,7 +165,6 @@ class AnalyticsServiceRestTransport(AnalyticsServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -229,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -315,19 +295,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ExportAnalyticsMetrics(AnalyticsServiceRestStub): + class _ExportAnalyticsMetrics( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics, + AnalyticsServiceRestStub, + ): def __hash__(self): - return hash("ExportAnalyticsMetrics") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("AnalyticsServiceRestTransport.ExportAnalyticsMetrics") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -357,47 +353,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", - "body": "*", - }, - ] + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_http_options() + ) request, metadata = self._interceptor.pre_export_analytics_metrics( request, metadata ) - pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + AnalyticsServiceRestTransport._ExportAnalyticsMetrics._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -425,7 +410,34 @@ def export_analytics_metrics( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(AnalyticsServiceRestStub): + class _GetOperation( + _BaseAnalyticsServiceRestTransport._BaseGetOperation, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -449,44 +461,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -494,8 +489,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -503,7 +499,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(AnalyticsServiceRestStub): + class _ListOperations( + _BaseAnalyticsServiceRestTransport._BaseListOperations, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -527,40 +550,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -568,8 +578,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest_base.py new file mode 100644 index 000000000000..998d884675e0 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/analytics_service/transports/rest_base.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import export_config + +from .base import DEFAULT_CLIENT_INFO, AnalyticsServiceTransport + + +class _BaseAnalyticsServiceRestTransport(AnalyticsServiceTransport): + """Base REST backend transport for AnalyticsService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseExportAnalyticsMetrics: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAnalyticsServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/async_client.py index c62160e6d8fb..8548628b5378 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/async_client.py @@ -1587,11 +1587,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1644,11 +1640,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/client.py index ae5150664236..e0e86217330f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/client.py @@ -2053,11 +2053,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2110,11 +2106,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/README.rst new file mode 100644 index 000000000000..c14dcbeef235 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CatalogServiceTransport` is the ABC for all transports. +- public child `CatalogServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CatalogServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCatalogServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CatalogServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/base.py index 08c2b5da536d..8e8353395ea8 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/base.py @@ -188,6 +188,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py index 1e5f0483b725..65618a6c85ca 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -633,66 +637,85 @@ def replace_catalog_attribute( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_catalogs: gapic_v1.method_async.wrap_method( + self.list_catalogs: self._wrap_method( self.list_catalogs, default_timeout=None, client_info=client_info, ), - self.update_catalog: gapic_v1.method_async.wrap_method( + self.update_catalog: self._wrap_method( self.update_catalog, default_timeout=None, client_info=client_info, ), - self.set_default_branch: gapic_v1.method_async.wrap_method( + self.set_default_branch: self._wrap_method( self.set_default_branch, default_timeout=None, client_info=client_info, ), - self.get_default_branch: gapic_v1.method_async.wrap_method( + self.get_default_branch: self._wrap_method( self.get_default_branch, default_timeout=None, client_info=client_info, ), - self.get_completion_config: gapic_v1.method_async.wrap_method( + self.get_completion_config: self._wrap_method( self.get_completion_config, default_timeout=None, client_info=client_info, ), - self.update_completion_config: gapic_v1.method_async.wrap_method( + self.update_completion_config: self._wrap_method( self.update_completion_config, default_timeout=None, client_info=client_info, ), - self.get_attributes_config: gapic_v1.method_async.wrap_method( + self.get_attributes_config: self._wrap_method( self.get_attributes_config, default_timeout=None, client_info=client_info, ), - self.update_attributes_config: gapic_v1.method_async.wrap_method( + self.update_attributes_config: self._wrap_method( self.update_attributes_config, default_timeout=None, client_info=client_info, ), - self.add_catalog_attribute: gapic_v1.method_async.wrap_method( + self.add_catalog_attribute: self._wrap_method( self.add_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.remove_catalog_attribute: gapic_v1.method_async.wrap_method( + self.remove_catalog_attribute: self._wrap_method( self.remove_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.replace_catalog_attribute: gapic_v1.method_async.wrap_method( + self.replace_catalog_attribute: self._wrap_method( self.replace_catalog_attribute, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest.py index a11481f2493e..3121b8064443 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2.types import catalog from google.cloud.retail_v2.types import catalog as gcr_catalog from google.cloud.retail_v2.types import catalog_service -from .base import CatalogServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCatalogServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -461,8 +457,8 @@ class CatalogServiceRestStub: _interceptor: CatalogServiceRestInterceptor -class CatalogServiceRestTransport(CatalogServiceTransport): - """REST backend transport for CatalogService. +class CatalogServiceRestTransport(_BaseCatalogServiceRestTransport): + """REST backend synchronous transport for CatalogService. Service for managing catalog configuration. @@ -471,7 +467,6 @@ class CatalogServiceRestTransport(CatalogServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -525,21 +520,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -550,19 +536,35 @@ def __init__( self._interceptor = interceptor or CatalogServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddCatalogAttribute(CatalogServiceRestStub): + class _AddCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("AddCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.AddCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -590,47 +592,34 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_add_catalog_attribute( request, metadata ) - pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._AddCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -646,19 +635,34 @@ def __call__( resp = self._interceptor.post_add_catalog_attribute(resp) return resp - class _GetAttributesConfig(CatalogServiceRestStub): + class _GetAttributesConfig( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -686,40 +690,29 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/attributesConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_attributes_config( request, metadata ) - pb_request = catalog_service.GetAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -735,19 +728,34 @@ def __call__( resp = self._interceptor.post_get_attributes_config(resp) return resp - class _GetCompletionConfig(CatalogServiceRestStub): + class _GetCompletionConfig( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -778,40 +786,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/completionConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_completion_config( request, metadata ) - pb_request = catalog_service.GetCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -827,9 +824,33 @@ def __call__( resp = self._interceptor.post_get_completion_config(resp) return resp - class _GetDefaultBranch(CatalogServiceRestStub): + class _GetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("GetDefaultBranch") + return hash("CatalogServiceRestTransport.GetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -858,39 +879,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_get_default_branch( request, metadata ) - pb_request = catalog_service.GetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = CatalogServiceRestTransport._GetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -906,19 +917,33 @@ def __call__( resp = self._interceptor.post_get_default_branch(resp) return resp - class _ListCatalogs(CatalogServiceRestStub): + class _ListCatalogs( + _BaseCatalogServiceRestTransport._BaseListCatalogs, CatalogServiceRestStub + ): def __hash__(self): - return hash("ListCatalogs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ListCatalogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -949,38 +974,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*}/catalogs", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_http_options() + ) request, metadata = self._interceptor.pre_list_catalogs(request, metadata) - pb_request = catalog_service.ListCatalogsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._ListCatalogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -996,19 +1010,35 @@ def __call__( resp = self._interceptor.post_list_catalogs(resp) return resp - class _RemoveCatalogAttribute(CatalogServiceRestStub): + class _RemoveCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("RemoveCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.RemoveCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1036,47 +1066,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_remove_catalog_attribute( request, metadata ) - pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._RemoveCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1092,19 +1111,35 @@ def __call__( resp = self._interceptor.post_remove_catalog_attribute(resp) return resp - class _ReplaceCatalogAttribute(CatalogServiceRestStub): + class _ReplaceCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("ReplaceCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ReplaceCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1132,47 +1167,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_replace_catalog_attribute( request, metadata ) - pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._ReplaceCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1188,9 +1212,34 @@ def __call__( resp = self._interceptor.post_replace_catalog_attribute(resp) return resp - class _SetDefaultBranch(CatalogServiceRestStub): + class _SetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("SetDefaultBranch") + return hash("CatalogServiceRestTransport.SetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1213,46 +1262,34 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_set_default_branch( request, metadata ) - pb_request = catalog_service.SetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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, + response = CatalogServiceRestTransport._SetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1260,19 +1297,35 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateAttributesConfig(CatalogServiceRestStub): + class _UpdateAttributesConfig( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1300,47 +1353,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", - "body": "attributes_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_attributes_config( request, metadata ) - pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1356,19 +1398,34 @@ def __call__( resp = self._interceptor.post_update_attributes_config(resp) return resp - class _UpdateCatalog(CatalogServiceRestStub): + class _UpdateCatalog( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog, CatalogServiceRestStub + ): def __hash__(self): - return hash("UpdateCatalog") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1396,45 +1453,32 @@ def __call__( The catalog configuration. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{catalog.name=projects/*/locations/*/catalogs/*}", - "body": "catalog", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_http_options() + ) request, metadata = self._interceptor.pre_update_catalog(request, metadata) - pb_request = catalog_service.UpdateCatalogRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._UpdateCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1450,19 +1494,35 @@ def __call__( resp = self._interceptor.post_update_catalog(resp) return resp - class _UpdateCompletionConfig(CatalogServiceRestStub): + class _UpdateCompletionConfig( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1493,47 +1553,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", - "body": "completion_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_completion_config( request, metadata ) - pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1660,7 +1709,34 @@ def update_completion_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CatalogServiceRestStub): + class _GetOperation( + _BaseCatalogServiceRestTransport._BaseGetOperation, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1684,44 +1760,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1729,8 +1788,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1738,7 +1798,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CatalogServiceRestStub): + class _ListOperations( + _BaseCatalogServiceRestTransport._BaseListOperations, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1762,40 +1849,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1803,8 +1877,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest_base.py new file mode 100644 index 000000000000..d3abb39731ec --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/catalog_service/transports/rest_base.py @@ -0,0 +1,723 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import catalog +from google.cloud.retail_v2.types import catalog as gcr_catalog +from google.cloud.retail_v2.types import catalog_service + +from .base import DEFAULT_CLIENT_INFO, CatalogServiceTransport + + +class _BaseCatalogServiceRestTransport(CatalogServiceTransport): + """Base REST backend transport for CatalogService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/attributesConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/completionConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCatalogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/catalogs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ListCatalogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseReplaceCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.SetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", + "body": "attributes_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{catalog.name=projects/*/locations/*/catalogs/*}", + "body": "catalog", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", + "body": "completion_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCatalogServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/async_client.py index 853078692f73..067ed974e49b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/async_client.py @@ -504,11 +504,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -561,11 +557,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/client.py index 4627b8d26d06..36e367811959 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/client.py @@ -937,11 +937,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -994,11 +990,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/README.rst new file mode 100644 index 000000000000..3f71883905ca --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CompletionServiceTransport` is the ABC for all transports. +- public child `CompletionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CompletionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCompletionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CompletionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/base.py index 796fd687de1c..4f18ae56a444 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/base.py @@ -140,6 +140,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py index e86d481dbf6d..52703fa6b586 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -336,21 +340,40 @@ def import_completion_data( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.complete_query: gapic_v1.method_async.wrap_method( + self.complete_query: self._wrap_method( self.complete_query, default_timeout=None, client_info=client_info, ), - self.import_completion_data: gapic_v1.method_async.wrap_method( + self.import_completion_data: self._wrap_method( self.import_completion_data, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest.py index 1ba6182de24e..a88b178415ed 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCompletionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2.types import completion_service, import_config - -from .base import CompletionServiceTransport -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, @@ -194,8 +184,8 @@ class CompletionServiceRestStub: _interceptor: CompletionServiceRestInterceptor -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. +class CompletionServiceRestTransport(_BaseCompletionServiceRestTransport): + """REST backend synchronous transport for CompletionService. Autocomplete service for retail. @@ -208,7 +198,6 @@ class CompletionServiceRestTransport(CompletionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -262,21 +251,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -348,21 +328,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CompleteQuery(CompletionServiceRestStub): + class _CompleteQuery( + _BaseCompletionServiceRestTransport._BaseCompleteQuery, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query": "", - } - - @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 - } + return hash("CompletionServiceRestTransport.CompleteQuery") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -388,38 +381,27 @@ def __call__( Response of the autocomplete query. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_http_options() + ) request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CompletionServiceRestTransport._CompleteQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -435,19 +417,35 @@ def __call__( resp = self._interceptor.post_complete_query(resp) return resp - class _ImportCompletionData(CompletionServiceRestStub): + class _ImportCompletionData( + _BaseCompletionServiceRestTransport._BaseImportCompletionData, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("ImportCompletionData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CompletionServiceRestTransport.ImportCompletionData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -477,47 +475,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/completionData:import", - "body": "*", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_http_options() + ) request, metadata = self._interceptor.pre_import_completion_data( request, metadata ) - pb_request = import_config.ImportCompletionDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CompletionServiceRestTransport._ImportCompletionData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -556,7 +543,34 @@ def import_completion_data( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CompletionServiceRestStub): + class _GetOperation( + _BaseCompletionServiceRestTransport._BaseGetOperation, CompletionServiceRestStub + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -580,44 +594,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -625,8 +622,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -634,7 +632,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CompletionServiceRestStub): + class _ListOperations( + _BaseCompletionServiceRestTransport._BaseListOperations, + CompletionServiceRestStub, + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -658,40 +684,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -699,8 +712,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest_base.py new file mode 100644 index 000000000000..65a2b8eb3a98 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/completion_service/transports/rest_base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO, CompletionServiceTransport + + +class _BaseCompletionServiceRestTransport(CompletionServiceTransport): + """Base REST backend transport for CompletionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCompleteQuery: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportCompletionData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/completionData:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportCompletionDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCompletionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/async_client.py index 4ada9e12dbaa..89361f717088 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/async_client.py @@ -889,11 +889,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -946,11 +942,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/client.py index b28ecd5b81bc..e8bde0f1318e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/client.py @@ -1332,11 +1332,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1389,11 +1385,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/README.rst new file mode 100644 index 000000000000..ee9c627694ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ControlServiceTransport` is the ABC for all transports. +- public child `ControlServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ControlServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseControlServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ControlServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/base.py index c16a6a26bb4d..402e8c509bf0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/grpc_asyncio.py index a846c27fc89b..427cd7f79de9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -395,36 +399,55 @@ def list_controls( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_control: gapic_v1.method_async.wrap_method( + self.create_control: self._wrap_method( self.create_control, default_timeout=None, client_info=client_info, ), - self.delete_control: gapic_v1.method_async.wrap_method( + self.delete_control: self._wrap_method( self.delete_control, default_timeout=None, client_info=client_info, ), - self.update_control: gapic_v1.method_async.wrap_method( + self.update_control: self._wrap_method( self.update_control, default_timeout=None, client_info=client_info, ), - self.get_control: gapic_v1.method_async.wrap_method( + self.get_control: self._wrap_method( self.get_control, default_timeout=None, client_info=client_info, ), - self.list_controls: gapic_v1.method_async.wrap_method( + self.list_controls: self._wrap_method( self.list_controls, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest.py index 051a8dfbd5dd..29f6cf5bd448 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2.types import control from google.cloud.retail_v2.types import control as gcr_control from google.cloud.retail_v2.types import control_service -from .base import ControlServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseControlServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -263,8 +259,8 @@ class ControlServiceRestStub: _interceptor: ControlServiceRestInterceptor -class ControlServiceRestTransport(ControlServiceTransport): - """REST backend transport for ControlService. +class ControlServiceRestTransport(_BaseControlServiceRestTransport): + """REST backend synchronous transport for ControlService. Service for modifying Control. @@ -273,7 +269,6 @@ class ControlServiceRestTransport(ControlServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -327,21 +322,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -352,21 +338,34 @@ def __init__( self._interceptor = interceptor or ControlServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateControl(ControlServiceRestStub): + class _CreateControl( + _BaseControlServiceRestTransport._BaseCreateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("CreateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "controlId": "", - } - - @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 - } + return hash("ControlServiceRestTransport.CreateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -396,45 +395,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/controls", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseCreateControl._get_http_options() + ) request, metadata = self._interceptor.pre_create_control(request, metadata) - pb_request = control_service.CreateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseCreateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseCreateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseCreateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._CreateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -450,19 +436,33 @@ def __call__( resp = self._interceptor.post_create_control(resp) return resp - class _DeleteControl(ControlServiceRestStub): + class _DeleteControl( + _BaseControlServiceRestTransport._BaseDeleteControl, ControlServiceRestStub + ): def __hash__(self): - return hash("DeleteControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.DeleteControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -484,38 +484,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseDeleteControl._get_http_options() + ) request, metadata = self._interceptor.pre_delete_control(request, metadata) - pb_request = control_service.DeleteControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseDeleteControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseDeleteControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._DeleteControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -523,19 +512,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetControl(ControlServiceRestStub): + class _GetControl( + _BaseControlServiceRestTransport._BaseGetControl, ControlServiceRestStub + ): def __hash__(self): - return hash("GetControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.GetControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -565,38 +568,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseGetControl._get_http_options() + ) request, metadata = self._interceptor.pre_get_control(request, metadata) - pb_request = control_service.GetControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseControlServiceRestTransport._BaseGetControl._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._GetControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -612,19 +606,33 @@ def __call__( resp = self._interceptor.post_get_control(resp) return resp - class _ListControls(ControlServiceRestStub): + class _ListControls( + _BaseControlServiceRestTransport._BaseListControls, ControlServiceRestStub + ): def __hash__(self): - return hash("ListControls") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.ListControls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -650,38 +658,27 @@ def __call__( Response for ListControls method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/controls", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseListControls._get_http_options() + ) request, metadata = self._interceptor.pre_list_controls(request, metadata) - pb_request = control_service.ListControlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListControls._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseListControls._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._ListControls._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -697,19 +694,34 @@ def __call__( resp = self._interceptor.post_list_controls(resp) return resp - class _UpdateControl(ControlServiceRestStub): + class _UpdateControl( + _BaseControlServiceRestTransport._BaseUpdateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("UpdateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.UpdateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -739,45 +751,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{control.name=projects/*/locations/*/catalogs/*/controls/*}", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseUpdateControl._get_http_options() + ) request, metadata = self._interceptor.pre_update_control(request, metadata) - pb_request = control_service.UpdateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseUpdateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseUpdateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseUpdateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._UpdateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -839,7 +838,34 @@ def update_control( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ControlServiceRestStub): + class _GetOperation( + _BaseControlServiceRestTransport._BaseGetOperation, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -863,44 +889,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -908,8 +917,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -917,7 +927,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ControlServiceRestStub): + class _ListOperations( + _BaseControlServiceRestTransport._BaseListOperations, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -941,40 +978,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -982,8 +1006,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest_base.py new file mode 100644 index 000000000000..07d6f66be79d --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/control_service/transports/rest_base.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import control +from google.cloud.retail_v2.types import control as gcr_control +from google.cloud.retail_v2.types import control_service + +from .base import DEFAULT_CLIENT_INFO, ControlServiceTransport + + +class _BaseControlServiceRestTransport(ControlServiceTransport): + """Base REST backend transport for ControlService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "controlId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/controls", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.CreateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseCreateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.DeleteControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseDeleteControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.GetControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseGetControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListControls: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/controls", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.ListControlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseListControls._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{control.name=projects/*/locations/*/catalogs/*/controls/*}", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.UpdateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseUpdateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseControlServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/async_client.py index a2ebf9328e94..6d32ddd95250 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/async_client.py @@ -962,11 +962,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1019,11 +1015,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/client.py index 49c8eb125faf..ac06b641fa6f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/client.py @@ -1388,11 +1388,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1445,11 +1441,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/README.rst new file mode 100644 index 000000000000..88a21803b12f --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GenerativeQuestionServiceTransport` is the ABC for all transports. +- public child `GenerativeQuestionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GenerativeQuestionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGenerativeQuestionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GenerativeQuestionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/base.py index 71e37adc0e19..233db1ba5de2 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/grpc_asyncio.py index 513bec5b30b3..721c0fa23e5a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -411,36 +415,55 @@ def batch_update_generative_question_configs( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.update_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.update_generative_questions_feature_config: self._wrap_method( self.update_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.get_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.get_generative_questions_feature_config: self._wrap_method( self.get_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.list_generative_question_configs: gapic_v1.method_async.wrap_method( + self.list_generative_question_configs: self._wrap_method( self.list_generative_question_configs, default_timeout=None, client_info=client_info, ), - self.update_generative_question_config: gapic_v1.method_async.wrap_method( + self.update_generative_question_config: self._wrap_method( self.update_generative_question_config, default_timeout=None, client_info=client_info, ), - self.batch_update_generative_question_configs: gapic_v1.method_async.wrap_method( + self.batch_update_generative_question_configs: self._wrap_method( self.batch_update_generative_question_configs, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest.py index cd9fc666b44a..5af114642001 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2.types import ( generative_question, generative_question_service, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import GenerativeQuestionServiceTransport +from .rest_base import _BaseGenerativeQuestionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -301,8 +297,10 @@ class GenerativeQuestionServiceRestStub: _interceptor: GenerativeQuestionServiceRestInterceptor -class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): - """REST backend transport for GenerativeQuestionService. +class GenerativeQuestionServiceRestTransport( + _BaseGenerativeQuestionServiceRestTransport +): + """REST backend synchronous transport for GenerativeQuestionService. Service for managing LLM generated questions in search serving. @@ -312,7 +310,6 @@ class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport) and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -366,21 +363,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -391,19 +379,37 @@ def __init__( self._interceptor = interceptor or GenerativeQuestionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _BatchUpdateGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _BatchUpdateGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("BatchUpdateGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.BatchUpdateGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -434,52 +440,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", - "body": "*", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_batch_update_generative_question_configs( request, metadata ) - pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._BatchUpdateGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -499,19 +490,36 @@ def __call__( resp = self._interceptor.post_batch_update_generative_question_configs(resp) return resp - class _GetGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _GetGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("GetGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.GetGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -542,45 +550,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_get_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._GetGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -596,19 +591,36 @@ def __call__( resp = self._interceptor.post_get_generative_questions_feature_config(resp) return resp - class _ListGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _ListGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("ListGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.ListGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -635,44 +647,29 @@ def __call__( Response for ListQuestions method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_generative_question_configs( request, metadata ) - pb_request = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._ListGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -692,19 +689,37 @@ def __call__( resp = self._interceptor.post_list_generative_question_configs(resp) return resp - class _UpdateGenerativeQuestionConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -734,51 +749,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", - "body": "generative_question_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_generative_question_config( request, metadata ) - pb_request = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +792,37 @@ def __call__( resp = self._interceptor.post_update_generative_question_config(resp) return resp - class _UpdateGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -837,52 +853,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - "body": "generative_questions_feature_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_update_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,7 +960,35 @@ def update_generative_questions_feature_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(GenerativeQuestionServiceRestStub): + class _GetOperation( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -983,44 +1012,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1028,8 +1042,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1037,7 +1052,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(GenerativeQuestionServiceRestStub): + class _ListOperations( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1061,40 +1104,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1102,8 +1134,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest_base.py new file mode 100644 index 000000000000..dcc479587e99 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/generative_question_service/transports/rest_base.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import ( + generative_question, + generative_question_service, +) + +from .base import DEFAULT_CLIENT_INFO, GenerativeQuestionServiceTransport + + +class _BaseGenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): + """Base REST backend transport for GenerativeQuestionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseBatchUpdateGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", + "body": "generative_question_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + "body": "generative_questions_feature_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseGenerativeQuestionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/async_client.py index a17f311a1ccd..7a192b41fdfa 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/async_client.py @@ -1244,11 +1244,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1301,11 +1297,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/client.py index 7b28f3e0a195..a569cffe9f3e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/client.py @@ -1677,11 +1677,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1734,11 +1730,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/README.rst new file mode 100644 index 000000000000..05dddc4c34ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ModelServiceTransport` is the ABC for all transports. +- public child `ModelServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ModelServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseModelServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ModelServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/base.py index e98b76bb17ea..9a38f6d10a6a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/base.py @@ -173,6 +173,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/grpc_asyncio.py index 27821db7a038..0f86ece481fd 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -243,6 +244,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -490,51 +494,70 @@ def tune_model( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_model: gapic_v1.method_async.wrap_method( + self.create_model: self._wrap_method( self.create_model, default_timeout=None, client_info=client_info, ), - self.get_model: gapic_v1.method_async.wrap_method( + self.get_model: self._wrap_method( self.get_model, default_timeout=None, client_info=client_info, ), - self.pause_model: gapic_v1.method_async.wrap_method( + self.pause_model: self._wrap_method( self.pause_model, default_timeout=None, client_info=client_info, ), - self.resume_model: gapic_v1.method_async.wrap_method( + self.resume_model: self._wrap_method( self.resume_model, default_timeout=None, client_info=client_info, ), - self.delete_model: gapic_v1.method_async.wrap_method( + self.delete_model: self._wrap_method( self.delete_model, default_timeout=None, client_info=client_info, ), - self.list_models: gapic_v1.method_async.wrap_method( + self.list_models: self._wrap_method( self.list_models, default_timeout=None, client_info=client_info, ), - self.update_model: gapic_v1.method_async.wrap_method( + self.update_model: self._wrap_method( self.update_model, default_timeout=None, client_info=client_info, ), - self.tune_model: gapic_v1.method_async.wrap_method( + self.tune_model: self._wrap_method( self.tune_model, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest.py index 8b0fb1ab1b5f..9255d6b786ca 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2.types import model from google.cloud.retail_v2.types import model as gcr_model from google.cloud.retail_v2.types import model_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ModelServiceTransport +from .rest_base import _BaseModelServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -360,8 +350,8 @@ class ModelServiceRestStub: _interceptor: ModelServiceRestInterceptor -class ModelServiceRestTransport(ModelServiceTransport): - """REST backend transport for ModelService. +class ModelServiceRestTransport(_BaseModelServiceRestTransport): + """REST backend synchronous transport for ModelService. Service for performing CRUD operations on models. Recommendation models contain all the metadata necessary to generate a set of @@ -381,7 +371,6 @@ class ModelServiceRestTransport(ModelServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -435,21 +424,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -521,19 +501,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateModel(ModelServiceRestStub): + class _CreateModel( + _BaseModelServiceRestTransport._BaseCreateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("CreateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.CreateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -562,45 +557,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/models", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_http_options() + ) request, metadata = self._interceptor.pre_create_model(request, metadata) - pb_request = model_service.CreateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._CreateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -614,19 +602,33 @@ def __call__( resp = self._interceptor.post_create_model(resp) return resp - class _DeleteModel(ModelServiceRestStub): + class _DeleteModel( + _BaseModelServiceRestTransport._BaseDeleteModel, ModelServiceRestStub + ): def __hash__(self): - return hash("DeleteModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.DeleteModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -648,38 +650,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_http_options() + ) request, metadata = self._interceptor.pre_delete_model(request, metadata) - pb_request = model_service.DeleteModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._DeleteModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -687,19 +682,31 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetModel(ModelServiceRestStub): + class _GetModel(_BaseModelServiceRestTransport._BaseGetModel, ModelServiceRestStub): def __hash__(self): - return hash("GetModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.GetModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -731,38 +738,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseGetModel._get_http_options() + ) request, metadata = self._interceptor.pre_get_model(request, metadata) - pb_request = model_service.GetModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseGetModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseGetModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._GetModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -778,19 +778,33 @@ def __call__( resp = self._interceptor.post_get_model(resp) return resp - class _ListModels(ModelServiceRestStub): + class _ListModels( + _BaseModelServiceRestTransport._BaseListModels, ModelServiceRestStub + ): def __hash__(self): - return hash("ListModels") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ListModels") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -817,38 +831,31 @@ def __call__( Response to a ListModelRequest. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/models", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseListModels._get_http_options() + ) request, metadata = self._interceptor.pre_list_models(request, metadata) - pb_request = model_service.ListModelsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseListModels._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseListModels._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._ListModels._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -864,19 +871,34 @@ def __call__( resp = self._interceptor.post_list_models(resp) return resp - class _PauseModel(ModelServiceRestStub): + class _PauseModel( + _BaseModelServiceRestTransport._BasePauseModel, ModelServiceRestStub + ): def __hash__(self): - return hash("PauseModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.PauseModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -909,45 +931,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:pause", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BasePauseModel._get_http_options() + ) request, metadata = self._interceptor.pre_pause_model(request, metadata) - pb_request = model_service.PauseModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BasePauseModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BasePauseModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BasePauseModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._PauseModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -963,19 +978,34 @@ def __call__( resp = self._interceptor.post_pause_model(resp) return resp - class _ResumeModel(ModelServiceRestStub): + class _ResumeModel( + _BaseModelServiceRestTransport._BaseResumeModel, ModelServiceRestStub + ): def __hash__(self): - return hash("ResumeModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ResumeModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1008,45 +1038,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:resume", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_http_options() + ) request, metadata = self._interceptor.pre_resume_model(request, metadata) - pb_request = model_service.ResumeModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._ResumeModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1062,19 +1085,34 @@ def __call__( resp = self._interceptor.post_resume_model(resp) return resp - class _TuneModel(ModelServiceRestStub): + class _TuneModel( + _BaseModelServiceRestTransport._BaseTuneModel, ModelServiceRestStub + ): def __hash__(self): - return hash("TuneModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.TuneModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1106,45 +1144,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:tune", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_http_options() + ) request, metadata = self._interceptor.pre_tune_model(request, metadata) - pb_request = model_service.TuneModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseModelServiceRestTransport._BaseTuneModel._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._TuneModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1158,19 +1187,34 @@ def __call__( resp = self._interceptor.post_tune_model(resp) return resp - class _UpdateModel(ModelServiceRestStub): + class _UpdateModel( + _BaseModelServiceRestTransport._BaseUpdateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("UpdateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.UpdateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1203,45 +1247,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{model.name=projects/*/locations/*/catalogs/*/models/*}", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_http_options() + ) request, metadata = self._interceptor.pre_update_model(request, metadata) - pb_request = model_service.UpdateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._UpdateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1319,7 +1356,34 @@ def update_model( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ModelServiceRestStub): + class _GetOperation( + _BaseModelServiceRestTransport._BaseGetOperation, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1343,44 +1407,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ModelServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1388,8 +1437,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1397,7 +1447,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ModelServiceRestStub): + class _ListOperations( + _BaseModelServiceRestTransport._BaseListOperations, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1421,40 +1498,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseModelServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ModelServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1462,8 +1526,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest_base.py new file mode 100644 index 000000000000..71fc7bae622c --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/model_service/transports/rest_base.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import model +from google.cloud.retail_v2.types import model as gcr_model +from google.cloud.retail_v2.types import model_service + +from .base import DEFAULT_CLIENT_INFO, ModelServiceTransport + + +class _BaseModelServiceRestTransport(ModelServiceTransport): + """Base REST backend transport for ModelService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/models", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.CreateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseCreateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.DeleteModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseDeleteModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.GetModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseGetModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListModels: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/models", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ListModelsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseListModels._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePauseModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:pause", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.PauseModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BasePauseModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseResumeModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:resume", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ResumeModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseResumeModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTuneModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/models/*}:tune", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.TuneModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseTuneModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{model.name=projects/*/locations/*/catalogs/*/models/*}", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.UpdateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseUpdateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseModelServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/async_client.py index fe2734fe3ff8..ccd1b99fc22f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/async_client.py @@ -377,11 +377,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -434,11 +430,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/client.py index 5bcc4a673241..035283d924a4 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/README.rst new file mode 100644 index 000000000000..504aaca0a144 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PredictionServiceTransport` is the ABC for all transports. +- public child `PredictionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PredictionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePredictionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PredictionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/base.py index d6687666bf23..b5a0bc2bb8ac 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py index 3d847d9c0f8d..0a7ddfa0f69a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -272,16 +276,35 @@ def predict( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.predict: gapic_v1.method_async.wrap_method( + self.predict: self._wrap_method( self.predict, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest.py index ff14b11dbeb4..0760606c0574 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePredictionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2.types import prediction_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PredictionServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -157,8 +153,8 @@ class PredictionServiceRestStub: _interceptor: PredictionServiceRestInterceptor -class PredictionServiceRestTransport(PredictionServiceTransport): - """REST backend transport for PredictionService. +class PredictionServiceRestTransport(_BasePredictionServiceRestTransport): + """REST backend synchronous transport for PredictionService. Service for making recommendation prediction. @@ -167,7 +163,6 @@ class PredictionServiceRestTransport(PredictionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -221,21 +216,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -246,19 +232,34 @@ def __init__( self._interceptor = interceptor or PredictionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Predict(PredictionServiceRestStub): + class _Predict( + _BasePredictionServiceRestTransport._BasePredict, PredictionServiceRestStub + ): def __hash__(self): - return hash("Predict") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PredictionServiceRestTransport.Predict") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -284,50 +285,36 @@ def __call__( Response message for predict method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", - "body": "*", - }, - { - "method": "post", - "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", - "body": "*", - }, - ] + http_options = ( + _BasePredictionServiceRestTransport._BasePredict._get_http_options() + ) request, metadata = self._interceptor.pre_predict(request, metadata) - pb_request = prediction_service.PredictRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePredictionServiceRestTransport._BasePredict._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BasePredictionServiceRestTransport._BasePredict._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BasePredictionServiceRestTransport._BasePredict._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PredictionServiceRestTransport._Predict._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -357,7 +344,34 @@ def predict( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(PredictionServiceRestStub): + class _GetOperation( + _BasePredictionServiceRestTransport._BaseGetOperation, PredictionServiceRestStub + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -381,44 +395,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -426,8 +423,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -435,7 +433,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(PredictionServiceRestStub): + class _ListOperations( + _BasePredictionServiceRestTransport._BaseListOperations, + PredictionServiceRestStub, + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -459,40 +485,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -500,8 +513,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest_base.py new file mode 100644 index 000000000000..a0c5c5dc92b9 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/prediction_service/transports/rest_base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO, PredictionServiceTransport + + +class _BasePredictionServiceRestTransport(PredictionServiceTransport): + """Base REST backend transport for PredictionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BasePredict: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_service.PredictRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionServiceRestTransport._BasePredict._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePredictionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/async_client.py index 1c37d91651f5..7aed6ad0e89f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/async_client.py @@ -2104,11 +2104,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2161,11 +2157,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/client.py index 6f3fda9dd91e..5767217f51e5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/client.py @@ -2534,11 +2534,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2591,11 +2587,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/README.rst new file mode 100644 index 000000000000..85a3f05c1f34 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProductServiceTransport` is the ABC for all transports. +- public child `ProductServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProductServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProductServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProductServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/base.py index 0b3f13dd6f8e..b4cdd0d61c07 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/base.py @@ -204,6 +204,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py index 2efb81a908fc..2e86340fb479 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -802,37 +806,37 @@ def remove_local_inventories( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_product: gapic_v1.method_async.wrap_method( + self.create_product: self._wrap_method( self.create_product, default_timeout=None, client_info=client_info, ), - self.get_product: gapic_v1.method_async.wrap_method( + self.get_product: self._wrap_method( self.get_product, default_timeout=None, client_info=client_info, ), - self.list_products: gapic_v1.method_async.wrap_method( + self.list_products: self._wrap_method( self.list_products, default_timeout=None, client_info=client_info, ), - self.update_product: gapic_v1.method_async.wrap_method( + self.update_product: self._wrap_method( self.update_product, default_timeout=None, client_info=client_info, ), - self.delete_product: gapic_v1.method_async.wrap_method( + self.delete_product: self._wrap_method( self.delete_product, default_timeout=None, client_info=client_info, ), - self.purge_products: gapic_v1.method_async.wrap_method( + self.purge_products: self._wrap_method( self.purge_products, default_timeout=None, client_info=client_info, ), - self.import_products: gapic_v1.method_async.wrap_method( + self.import_products: self._wrap_method( self.import_products, default_retry=retries.AsyncRetry( initial=0.1, @@ -847,36 +851,55 @@ def _prep_wrapped_messages(self, client_info): default_timeout=300.0, client_info=client_info, ), - self.set_inventory: gapic_v1.method_async.wrap_method( + self.set_inventory: self._wrap_method( self.set_inventory, default_timeout=None, client_info=client_info, ), - self.add_fulfillment_places: gapic_v1.method_async.wrap_method( + self.add_fulfillment_places: self._wrap_method( self.add_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.remove_fulfillment_places: gapic_v1.method_async.wrap_method( + self.remove_fulfillment_places: self._wrap_method( self.remove_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.add_local_inventories: gapic_v1.method_async.wrap_method( + self.add_local_inventories: self._wrap_method( self.add_local_inventories, default_timeout=None, client_info=client_info, ), - self.remove_local_inventories: gapic_v1.method_async.wrap_method( + self.remove_local_inventories: self._wrap_method( self.remove_local_inventories, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest.py index 2f547d840189..93d52a91f418 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest.py @@ -16,35 +16,19 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2.types import import_config from google.cloud.retail_v2.types import product @@ -52,7 +36,13 @@ from google.cloud.retail_v2.types import product_service, purge_config from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProductServiceTransport +from .rest_base import _BaseProductServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -491,8 +481,8 @@ class ProductServiceRestStub: _interceptor: ProductServiceRestInterceptor -class ProductServiceRestTransport(ProductServiceTransport): - """REST backend transport for ProductService. +class ProductServiceRestTransport(_BaseProductServiceRestTransport): + """REST backend synchronous transport for ProductService. Service for ingesting [Product][google.cloud.retail.v2.Product] information of the customer's website. @@ -502,7 +492,6 @@ class ProductServiceRestTransport(ProductServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -556,21 +545,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -642,19 +622,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _AddFulfillmentPlaces(ProductServiceRestStub): + class _AddFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -685,47 +681,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_add_fulfillment_places( request, metadata ) - pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -739,19 +722,35 @@ def __call__( resp = self._interceptor.post_add_fulfillment_places(resp) return resp - class _AddLocalInventories(ProductServiceRestStub): + class _AddLocalInventories( + _BaseProductServiceRestTransport._BaseAddLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -782,47 +781,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_add_local_inventories( request, metadata ) - pb_request = product_service.AddLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -836,21 +822,34 @@ def __call__( resp = self._interceptor.post_add_local_inventories(resp) return resp - class _CreateProduct(ProductServiceRestStub): + class _CreateProduct( + _BaseProductServiceRestTransport._BaseCreateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("CreateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "productId": "", - } - - @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 - } + return hash("ProductServiceRestTransport.CreateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -881,45 +880,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseCreateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_create_product(request, metadata) - pb_request = product_service.CreateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseCreateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseCreateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseCreateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._CreateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -935,19 +921,33 @@ def __call__( resp = self._interceptor.post_create_product(resp) return resp - class _DeleteProduct(ProductServiceRestStub): + class _DeleteProduct( + _BaseProductServiceRestTransport._BaseDeleteProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("DeleteProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.DeleteProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -971,38 +971,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_http_options() + ) request, metadata = self._interceptor.pre_delete_product(request, metadata) - pb_request = product_service.DeleteProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseDeleteProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseDeleteProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._DeleteProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1010,19 +999,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetProduct(ProductServiceRestStub): + class _GetProduct( + _BaseProductServiceRestTransport._BaseGetProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("GetProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.GetProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1053,38 +1056,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_http_options() + ) request, metadata = self._interceptor.pre_get_product(request, metadata) - pb_request = product_service.GetProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._GetProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1100,19 +1094,34 @@ def __call__( resp = self._interceptor.post_get_product(resp) return resp - class _ImportProducts(ProductServiceRestStub): + class _ImportProducts( + _BaseProductServiceRestTransport._BaseImportProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ImportProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ImportProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1141,45 +1150,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseImportProducts._get_http_options() + ) request, metadata = self._interceptor.pre_import_products(request, metadata) - pb_request = import_config.ImportProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseImportProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseImportProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseImportProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._ImportProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1193,19 +1189,33 @@ def __call__( resp = self._interceptor.post_import_products(resp) return resp - class _ListProducts(ProductServiceRestStub): + class _ListProducts( + _BaseProductServiceRestTransport._BaseListProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ListProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ListProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1236,38 +1246,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseListProducts._get_http_options() + ) request, metadata = self._interceptor.pre_list_products(request, metadata) - pb_request = product_service.ListProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListProducts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseListProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._ListProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1283,19 +1282,34 @@ def __call__( resp = self._interceptor.post_list_products(resp) return resp - class _PurgeProducts(ProductServiceRestStub): + class _PurgeProducts( + _BaseProductServiceRestTransport._BasePurgeProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("PurgeProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.PurgeProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1325,45 +1339,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BasePurgeProducts._get_http_options() + ) request, metadata = self._interceptor.pre_purge_products(request, metadata) - pb_request = purge_config.PurgeProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BasePurgeProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BasePurgeProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BasePurgeProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._PurgeProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1377,19 +1378,35 @@ def __call__( resp = self._interceptor.post_purge_products(resp) return resp - class _RemoveFulfillmentPlaces(ProductServiceRestStub): + class _RemoveFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1420,47 +1437,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_remove_fulfillment_places( request, metadata ) - pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1474,19 +1480,35 @@ def __call__( resp = self._interceptor.post_remove_fulfillment_places(resp) return resp - class _RemoveLocalInventories(ProductServiceRestStub): + class _RemoveLocalInventories( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1517,47 +1539,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_remove_local_inventories( request, metadata ) - pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1571,19 +1582,34 @@ def __call__( resp = self._interceptor.post_remove_local_inventories(resp) return resp - class _SetInventory(ProductServiceRestStub): + class _SetInventory( + _BaseProductServiceRestTransport._BaseSetInventory, ProductServiceRestStub + ): def __hash__(self): - return hash("SetInventory") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.SetInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1614,45 +1640,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseSetInventory._get_http_options() + ) request, metadata = self._interceptor.pre_set_inventory(request, metadata) - pb_request = product_service.SetInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseSetInventory._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseSetInventory._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseSetInventory._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._SetInventory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1666,19 +1679,34 @@ def __call__( resp = self._interceptor.post_set_inventory(resp) return resp - class _UpdateProduct(ProductServiceRestStub): + class _UpdateProduct( + _BaseProductServiceRestTransport._BaseUpdateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("UpdateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.UpdateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1709,45 +1737,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_update_product(request, metadata) - pb_request = product_service.UpdateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseUpdateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseUpdateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseUpdateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._UpdateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1873,7 +1888,34 @@ def update_product( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProductServiceRestStub): + class _GetOperation( + _BaseProductServiceRestTransport._BaseGetOperation, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1897,44 +1939,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1942,8 +1967,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1951,7 +1977,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ProductServiceRestStub): + class _ListOperations( + _BaseProductServiceRestTransport._BaseListOperations, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1975,40 +2028,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2016,8 +2056,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest_base.py new file mode 100644 index 000000000000..368255ddd436 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/product_service/transports/rest_base.py @@ -0,0 +1,823 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import import_config +from google.cloud.retail_v2.types import product +from google.cloud.retail_v2.types import product as gcr_product +from google.cloud.retail_v2.types import product_service, purge_config + +from .base import DEFAULT_CLIENT_INFO, ProductServiceTransport + + +class _BaseProductServiceRestTransport(ProductServiceTransport): + """Base REST backend transport for ProductService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseAddLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "productId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.CreateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseCreateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.DeleteProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.GetProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseGetProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseImportProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.ListProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseListProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BasePurgeProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.SetInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseSetInventory._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.UpdateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProductServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/async_client.py index c34b072bcd3e..249c2fcde448 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/async_client.py @@ -407,11 +407,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -464,11 +460,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/client.py index e7a64e1747f0..68c808fabcbe 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/client.py @@ -909,11 +909,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -966,11 +962,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/README.rst new file mode 100644 index 000000000000..8ef0891e3c25 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SearchServiceTransport` is the ABC for all transports. +- public child `SearchServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SearchServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSearchServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SearchServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/base.py index 091b6415ccc2..32ac73045a0d 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py index f0aa20d9abff..14fb279bc410 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -279,16 +283,35 @@ def search( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.search: gapic_v1.method_async.wrap_method( + self.search: self._wrap_method( self.search, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest.py index b78037b157c7..25759ceaf7dd 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2.types import search_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSearchServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2.types import search_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import SearchServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -155,8 +151,8 @@ class SearchServiceRestStub: _interceptor: SearchServiceRestInterceptor -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. +class SearchServiceRestTransport(_BaseSearchServiceRestTransport): + """REST backend synchronous transport for SearchService. Service for search. @@ -169,7 +165,6 @@ class SearchServiceRestTransport(SearchServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -223,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -248,19 +234,32 @@ def __init__( self._interceptor = interceptor or SearchServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Search(SearchServiceRestStub): + class _Search(_BaseSearchServiceRestTransport._BaseSearch, SearchServiceRestStub): def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SearchServiceRestTransport.Search") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -291,50 +290,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", - "body": "*", - }, - { - "method": "post", - "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", - "body": "*", - }, - ] + http_options = ( + _BaseSearchServiceRestTransport._BaseSearch._get_http_options() + ) request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseSearchServiceRestTransport._BaseSearch._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseSearchServiceRestTransport._BaseSearch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseSearchServiceRestTransport._BaseSearch._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = SearchServiceRestTransport._Search._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -362,7 +347,34 @@ def search( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(SearchServiceRestStub): + class _GetOperation( + _BaseSearchServiceRestTransport._BaseGetOperation, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -386,44 +398,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -431,8 +426,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -440,7 +436,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(SearchServiceRestStub): + class _ListOperations( + _BaseSearchServiceRestTransport._BaseListOperations, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -464,40 +487,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -505,8 +515,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest_base.py new file mode 100644 index 000000000000..c8676bfa5dd6 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/search_service/transports/rest_base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import search_service + +from .base import DEFAULT_CLIENT_INFO, SearchServiceTransport + + +class _BaseSearchServiceRestTransport(SearchServiceTransport): + """Base REST backend transport for SearchService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseSearch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSearchServiceRestTransport._BaseSearch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSearchServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/async_client.py index 9c0e995923a4..e9e72935d1d0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/async_client.py @@ -1144,11 +1144,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1201,11 +1197,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/client.py index 0100c7998a60..b0e65c6ac12c 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/client.py @@ -1580,11 +1580,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1637,11 +1633,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/README.rst new file mode 100644 index 000000000000..0581bb81c691 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ServingConfigServiceTransport` is the ABC for all transports. +- public child `ServingConfigServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ServingConfigServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseServingConfigServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ServingConfigServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/base.py index c05176b75d3b..98867d9a9365 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/base.py @@ -168,6 +168,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/grpc_asyncio.py index b66e668cfdf1..a796434d4513 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -467,46 +471,65 @@ def remove_control( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_serving_config: gapic_v1.method_async.wrap_method( + self.create_serving_config: self._wrap_method( self.create_serving_config, default_timeout=None, client_info=client_info, ), - self.delete_serving_config: gapic_v1.method_async.wrap_method( + self.delete_serving_config: self._wrap_method( self.delete_serving_config, default_timeout=None, client_info=client_info, ), - self.update_serving_config: gapic_v1.method_async.wrap_method( + self.update_serving_config: self._wrap_method( self.update_serving_config, default_timeout=None, client_info=client_info, ), - self.get_serving_config: gapic_v1.method_async.wrap_method( + self.get_serving_config: self._wrap_method( self.get_serving_config, default_timeout=None, client_info=client_info, ), - self.list_serving_configs: gapic_v1.method_async.wrap_method( + self.list_serving_configs: self._wrap_method( self.list_serving_configs, default_timeout=None, client_info=client_info, ), - self.add_control: gapic_v1.method_async.wrap_method( + self.add_control: self._wrap_method( self.add_control, default_timeout=None, client_info=client_info, ), - self.remove_control: gapic_v1.method_async.wrap_method( + self.remove_control: self._wrap_method( self.remove_control, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest.py index eba406198b73..8f38df345d1b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2.types import serving_config from google.cloud.retail_v2.types import serving_config as gcr_serving_config from google.cloud.retail_v2.types import serving_config_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ServingConfigServiceTransport +from .rest_base import _BaseServingConfigServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -341,8 +337,8 @@ class ServingConfigServiceRestStub: _interceptor: ServingConfigServiceRestInterceptor -class ServingConfigServiceRestTransport(ServingConfigServiceTransport): - """REST backend transport for ServingConfigService. +class ServingConfigServiceRestTransport(_BaseServingConfigServiceRestTransport): + """REST backend synchronous transport for ServingConfigService. Service for modifying ServingConfig. @@ -351,7 +347,6 @@ class ServingConfigServiceRestTransport(ServingConfigServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -405,21 +400,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -430,19 +416,35 @@ def __init__( self._interceptor = interceptor or ServingConfigServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddControl(ServingConfigServiceRestStub): + class _AddControl( + _BaseServingConfigServiceRestTransport._BaseAddControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("AddControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.AddControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -472,45 +474,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_http_options() + ) request, metadata = self._interceptor.pre_add_control(request, metadata) - pb_request = serving_config_service.AddControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseAddControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseAddControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseAddControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._AddControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -526,21 +515,35 @@ def __call__( resp = self._interceptor.post_add_control(resp) return resp - class _CreateServingConfig(ServingConfigServiceRestStub): + class _CreateServingConfig( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("CreateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "servingConfigId": "", - } - - @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 - } + return hash("ServingConfigServiceRestTransport.CreateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -571,47 +574,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_create_serving_config( request, metadata ) - pb_request = serving_config_service.CreateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._CreateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -627,19 +619,34 @@ def __call__( resp = self._interceptor.post_create_serving_config(resp) return resp - class _DeleteServingConfig(ServingConfigServiceRestStub): + class _DeleteServingConfig( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("DeleteServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.DeleteServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -662,40 +669,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_delete_serving_config( request, metadata ) - pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._DeleteServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -703,19 +701,34 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetServingConfig(ServingConfigServiceRestStub): + class _GetServingConfig( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("GetServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.GetServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -745,40 +758,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_serving_config( request, metadata ) - pb_request = serving_config_service.GetServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._GetServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +798,34 @@ def __call__( resp = self._interceptor.post_get_serving_config(resp) return resp - class _ListServingConfigs(ServingConfigServiceRestStub): + class _ListServingConfigs( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("ListServingConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.ListServingConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -835,40 +854,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_serving_configs( request, metadata ) - pb_request = serving_config_service.ListServingConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._ListServingConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -884,19 +894,35 @@ def __call__( resp = self._interceptor.post_list_serving_configs(resp) return resp - class _RemoveControl(ServingConfigServiceRestStub): + class _RemoveControl( + _BaseServingConfigServiceRestTransport._BaseRemoveControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("RemoveControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.RemoveControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -926,45 +952,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_http_options() + ) request, metadata = self._interceptor.pre_remove_control(request, metadata) - pb_request = serving_config_service.RemoveControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._RemoveControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -980,19 +993,35 @@ def __call__( resp = self._interceptor.post_remove_control(resp) return resp - class _UpdateServingConfig(ServingConfigServiceRestStub): + class _UpdateServingConfig( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("UpdateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.UpdateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1023,47 +1052,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_serving_config( request, metadata ) - pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._UpdateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1154,7 +1172,35 @@ def update_serving_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ServingConfigServiceRestStub): + class _GetOperation( + _BaseServingConfigServiceRestTransport._BaseGetOperation, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1178,44 +1224,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1223,8 +1252,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1232,7 +1262,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ServingConfigServiceRestStub): + class _ListOperations( + _BaseServingConfigServiceRestTransport._BaseListOperations, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1256,40 +1314,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1297,8 +1342,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest_base.py new file mode 100644 index 000000000000..109502880aaa --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/serving_config_service/transports/rest_base.py @@ -0,0 +1,537 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import serving_config +from google.cloud.retail_v2.types import serving_config as gcr_serving_config +from google.cloud.retail_v2.types import serving_config_service + +from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport + + +class _BaseServingConfigServiceRestTransport(ServingConfigServiceTransport): + """Base REST backend transport for ServingConfigService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.AddControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "servingConfigId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.CreateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.GetServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServingConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.ListServingConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.RemoveControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseServingConfigServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/async_client.py index 7d3f83d499bc..481c96bbaae1 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/async_client.py @@ -860,11 +860,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -917,11 +913,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/client.py index 16706313d944..7e7a0aa538a2 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/client.py @@ -1311,11 +1311,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1368,11 +1364,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/README.rst new file mode 100644 index 000000000000..45f0ef746528 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserEventServiceTransport` is the ABC for all transports. +- public child `UserEventServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserEventServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserEventServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserEventServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/base.py index 53dfb5d3da91..e92231166d14 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/base.py @@ -181,6 +181,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py index 1a935e1d5a4e..63fdd579a30d 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -236,6 +237,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -434,17 +438,17 @@ def rejoin_user_events( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.write_user_event: gapic_v1.method_async.wrap_method( + self.write_user_event: self._wrap_method( self.write_user_event, default_timeout=None, client_info=client_info, ), - self.collect_user_event: gapic_v1.method_async.wrap_method( + self.collect_user_event: self._wrap_method( self.collect_user_event, default_timeout=None, client_info=client_info, ), - self.purge_user_events: gapic_v1.method_async.wrap_method( + self.purge_user_events: self._wrap_method( self.purge_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -459,7 +463,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), - self.import_user_events: gapic_v1.method_async.wrap_method( + self.import_user_events: self._wrap_method( self.import_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -474,16 +478,35 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.rejoin_user_events: gapic_v1.method_async.wrap_method( + self.rejoin_user_events: self._wrap_method( self.rejoin_user_events, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest.py index c2d5d5cbabfa..6a923ae65b1a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest.py @@ -16,36 +16,20 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2.types import ( import_config, purge_config, @@ -54,7 +38,13 @@ ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import UserEventServiceTransport +from .rest_base import _BaseUserEventServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -293,8 +283,8 @@ class UserEventServiceRestStub: _interceptor: UserEventServiceRestInterceptor -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. +class UserEventServiceRestTransport(_BaseUserEventServiceRestTransport): + """REST backend synchronous transport for UserEventService. Service for ingesting end user actions on the customer website. @@ -304,7 +294,6 @@ class UserEventServiceRestTransport(UserEventServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -358,21 +347,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -444,21 +424,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CollectUserEvent(UserEventServiceRestStub): + class _CollectUserEvent( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent": "", - } - - @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 - } + return hash("UserEventServiceRestTransport.CollectUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -534,40 +527,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_collect_user_event( request, metadata ) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = UserEventServiceRestTransport._CollectUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -583,19 +565,35 @@ def __call__( resp = self._interceptor.post_collect_user_event(resp) return resp - class _ImportUserEvents(UserEventServiceRestStub): + class _ImportUserEvents( + _BaseUserEventServiceRestTransport._BaseImportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ImportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -625,47 +623,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_import_user_events( request, metadata ) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ImportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -679,19 +664,35 @@ def __call__( resp = self._interceptor.post_import_user_events(resp) return resp - class _PurgeUserEvents(UserEventServiceRestStub): + class _PurgeUserEvents( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("PurgeUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.PurgeUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -721,47 +722,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_purge_user_events( request, metadata ) - pb_request = purge_config.PurgeUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._PurgeUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -775,19 +763,35 @@ def __call__( resp = self._interceptor.post_purge_user_events(resp) return resp - class _RejoinUserEvents(UserEventServiceRestStub): + class _RejoinUserEvents( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("RejoinUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.RejoinUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -817,47 +821,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_rejoin_user_events( request, metadata ) - pb_request = user_event_service.RejoinUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._RejoinUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -871,19 +862,34 @@ def __call__( resp = self._interceptor.post_rejoin_user_events(resp) return resp - class _WriteUserEvent(UserEventServiceRestStub): + class _WriteUserEvent( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent, UserEventServiceRestStub + ): def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.WriteUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -914,47 +920,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", - "body": "user_event", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_write_user_event( request, metadata ) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._WriteUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1016,7 +1009,34 @@ def write_user_event( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(UserEventServiceRestStub): + class _GetOperation( + _BaseUserEventServiceRestTransport._BaseGetOperation, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1040,44 +1060,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1085,8 +1088,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1094,7 +1098,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(UserEventServiceRestStub): + class _ListOperations( + _BaseUserEventServiceRestTransport._BaseListOperations, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1118,40 +1149,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1159,8 +1177,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest_base.py new file mode 100644 index 000000000000..991095b65a0f --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2/services/user_event_service/transports/rest_base.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2.types import ( + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + + +class _BaseUserEventServiceRestTransport(UserEventServiceTransport): + """Base REST backend transport for UserEventService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCollectUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRejoinUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.RejoinUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseWriteUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", + "body": "user_event", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseUserEventServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py index 8b80cf328714..558c8aab67c5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/async_client.py index fe7fa1bd08ac..4576fcceb181 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/async_client.py @@ -403,11 +403,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -460,11 +456,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/client.py index c0e513732f90..37a249e76a9a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/README.rst new file mode 100644 index 000000000000..cf1d5125ad04 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AnalyticsServiceTransport` is the ABC for all transports. +- public child `AnalyticsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AnalyticsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAnalyticsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AnalyticsServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/base.py index 07905a9ab00f..a2fe6c5c4385 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/base.py @@ -145,6 +145,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/grpc_asyncio.py index 29bea3551ff4..43cb36b2d910 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -295,7 +299,7 @@ def export_analytics_metrics( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.export_analytics_metrics: gapic_v1.method_async.wrap_method( + self.export_analytics_metrics: self._wrap_method( self.export_analytics_metrics, default_retry=retries.AsyncRetry( initial=0.1, @@ -310,11 +314,30 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest.py index 7841fcf1d399..1a7a7eab81f4 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import export_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAnalyticsServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import export_config - -from .base import AnalyticsServiceTransport -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, @@ -163,8 +153,8 @@ class AnalyticsServiceRestStub: _interceptor: AnalyticsServiceRestInterceptor -class AnalyticsServiceRestTransport(AnalyticsServiceTransport): - """REST backend transport for AnalyticsService. +class AnalyticsServiceRestTransport(_BaseAnalyticsServiceRestTransport): + """REST backend synchronous transport for AnalyticsService. Service for managing & accessing retail search business metric. Retail recommendation business metric is currently not @@ -175,7 +165,6 @@ class AnalyticsServiceRestTransport(AnalyticsServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -229,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -319,19 +299,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ExportAnalyticsMetrics(AnalyticsServiceRestStub): + class _ExportAnalyticsMetrics( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics, + AnalyticsServiceRestStub, + ): def __hash__(self): - return hash("ExportAnalyticsMetrics") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("AnalyticsServiceRestTransport.ExportAnalyticsMetrics") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -361,47 +357,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", - "body": "*", - }, - ] + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_http_options() + ) request, metadata = self._interceptor.pre_export_analytics_metrics( request, metadata ) - pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + AnalyticsServiceRestTransport._ExportAnalyticsMetrics._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -429,7 +414,34 @@ def export_analytics_metrics( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(AnalyticsServiceRestStub): + class _GetOperation( + _BaseAnalyticsServiceRestTransport._BaseGetOperation, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -453,48 +465,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -502,8 +493,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -511,7 +503,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(AnalyticsServiceRestStub): + class _ListOperations( + _BaseAnalyticsServiceRestTransport._BaseListOperations, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -535,40 +554,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -576,8 +582,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest_base.py new file mode 100644 index 000000000000..0ccb3731a91d --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/analytics_service/transports/rest_base.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import export_config + +from .base import DEFAULT_CLIENT_INFO, AnalyticsServiceTransport + + +class _BaseAnalyticsServiceRestTransport(AnalyticsServiceTransport): + """Base REST backend transport for AnalyticsService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseExportAnalyticsMetrics: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAnalyticsServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/async_client.py index eb3991f294a3..bdb252bcdf77 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/async_client.py @@ -520,11 +520,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -577,11 +573,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/client.py index b21b2b52e906..26c484a6c220 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/client.py @@ -994,11 +994,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1051,11 +1047,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/README.rst new file mode 100644 index 000000000000..368e99419f04 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BranchServiceTransport` is the ABC for all transports. +- public child `BranchServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BranchServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBranchServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BranchServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/base.py index 5ba43bb432e4..67751183ba58 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/base.py @@ -140,6 +140,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/grpc_asyncio.py index 2d1891f2b751..ba36d03cc32a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -306,21 +310,40 @@ def get_branch( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_branches: gapic_v1.method_async.wrap_method( + self.list_branches: self._wrap_method( self.list_branches, default_timeout=None, client_info=client_info, ), - self.get_branch: gapic_v1.method_async.wrap_method( + self.get_branch: self._wrap_method( self.get_branch, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest.py index 2c0376fd3259..797e54c34a7f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import branch, branch_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBranchServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import branch, branch_service - -from .base import BranchServiceTransport -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, @@ -186,8 +182,8 @@ class BranchServiceRestStub: _interceptor: BranchServiceRestInterceptor -class BranchServiceRestTransport(BranchServiceTransport): - """REST backend transport for BranchService. +class BranchServiceRestTransport(_BaseBranchServiceRestTransport): + """REST backend synchronous transport for BranchService. Service for [Branch][google.cloud.retail.v2alpha.Branch] Management @@ -202,7 +198,6 @@ class BranchServiceRestTransport(BranchServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -256,21 +251,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -281,19 +267,33 @@ def __init__( self._interceptor = interceptor or BranchServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetBranch(BranchServiceRestStub): + class _GetBranch( + _BaseBranchServiceRestTransport._BaseGetBranch, BranchServiceRestStub + ): def __hash__(self): - return hash("GetBranch") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("BranchServiceRestTransport.GetBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -323,38 +323,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*}", - }, - ] + http_options = ( + _BaseBranchServiceRestTransport._BaseGetBranch._get_http_options() + ) request, metadata = self._interceptor.pre_get_branch(request, metadata) - pb_request = branch_service.GetBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseBranchServiceRestTransport._BaseGetBranch._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseBranchServiceRestTransport._BaseGetBranch._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = BranchServiceRestTransport._GetBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -370,19 +363,33 @@ def __call__( resp = self._interceptor.post_get_branch(resp) return resp - class _ListBranches(BranchServiceRestStub): + class _ListBranches( + _BaseBranchServiceRestTransport._BaseListBranches, BranchServiceRestStub + ): def __hash__(self): - return hash("ListBranches") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("BranchServiceRestTransport.ListBranches") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -413,38 +420,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/branches", - }, - ] + http_options = ( + _BaseBranchServiceRestTransport._BaseListBranches._get_http_options() + ) request, metadata = self._interceptor.pre_list_branches(request, metadata) - pb_request = branch_service.ListBranchesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseBranchServiceRestTransport._BaseListBranches._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseBranchServiceRestTransport._BaseListBranches._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = BranchServiceRestTransport._ListBranches._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -480,7 +476,34 @@ def list_branches( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(BranchServiceRestStub): + class _GetOperation( + _BaseBranchServiceRestTransport._BaseGetOperation, BranchServiceRestStub + ): + def __hash__(self): + return hash("BranchServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -504,48 +527,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseBranchServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseBranchServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseBranchServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = BranchServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -553,8 +555,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -562,7 +565,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(BranchServiceRestStub): + class _ListOperations( + _BaseBranchServiceRestTransport._BaseListOperations, BranchServiceRestStub + ): + def __hash__(self): + return hash("BranchServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -586,40 +616,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseBranchServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseBranchServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseBranchServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = BranchServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -627,8 +644,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest_base.py new file mode 100644 index 000000000000..4f2c02b1de3c --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/branch_service/transports/rest_base.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import branch, branch_service + +from .base import DEFAULT_CLIENT_INFO, BranchServiceTransport + + +class _BaseBranchServiceRestTransport(BranchServiceTransport): + """Base REST backend transport for BranchService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = branch_service.GetBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBranchServiceRestTransport._BaseGetBranch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListBranches: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/branches", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = branch_service.ListBranchesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBranchServiceRestTransport._BaseListBranches._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseBranchServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/async_client.py index 501b14c89a7c..76878b2445d5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/async_client.py @@ -1685,11 +1685,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1742,11 +1738,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/client.py index 90d73619066c..00b001ac536c 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/client.py @@ -2151,11 +2151,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2208,11 +2204,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/README.rst new file mode 100644 index 000000000000..c14dcbeef235 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CatalogServiceTransport` is the ABC for all transports. +- public child `CatalogServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CatalogServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCatalogServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CatalogServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py index c3b8f8ba24f2..dabde593f39e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/base.py @@ -193,6 +193,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py index e18e3a3c940b..1a3120463217 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -671,71 +675,90 @@ def replace_catalog_attribute( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_catalogs: gapic_v1.method_async.wrap_method( + self.list_catalogs: self._wrap_method( self.list_catalogs, default_timeout=None, client_info=client_info, ), - self.update_catalog: gapic_v1.method_async.wrap_method( + self.update_catalog: self._wrap_method( self.update_catalog, default_timeout=None, client_info=client_info, ), - self.set_default_branch: gapic_v1.method_async.wrap_method( + self.set_default_branch: self._wrap_method( self.set_default_branch, default_timeout=None, client_info=client_info, ), - self.get_default_branch: gapic_v1.method_async.wrap_method( + self.get_default_branch: self._wrap_method( self.get_default_branch, default_timeout=None, client_info=client_info, ), - self.get_completion_config: gapic_v1.method_async.wrap_method( + self.get_completion_config: self._wrap_method( self.get_completion_config, default_timeout=None, client_info=client_info, ), - self.update_completion_config: gapic_v1.method_async.wrap_method( + self.update_completion_config: self._wrap_method( self.update_completion_config, default_timeout=None, client_info=client_info, ), - self.get_attributes_config: gapic_v1.method_async.wrap_method( + self.get_attributes_config: self._wrap_method( self.get_attributes_config, default_timeout=None, client_info=client_info, ), - self.update_attributes_config: gapic_v1.method_async.wrap_method( + self.update_attributes_config: self._wrap_method( self.update_attributes_config, default_timeout=None, client_info=client_info, ), - self.add_catalog_attribute: gapic_v1.method_async.wrap_method( + self.add_catalog_attribute: self._wrap_method( self.add_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.remove_catalog_attribute: gapic_v1.method_async.wrap_method( + self.remove_catalog_attribute: self._wrap_method( self.remove_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.batch_remove_catalog_attributes: gapic_v1.method_async.wrap_method( + self.batch_remove_catalog_attributes: self._wrap_method( self.batch_remove_catalog_attributes, default_timeout=None, client_info=client_info, ), - self.replace_catalog_attribute: gapic_v1.method_async.wrap_method( + self.replace_catalog_attribute: self._wrap_method( self.replace_catalog_attribute, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest.py index 84ddb4d85f8e..3cbcf9b99662 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2alpha.types import catalog from google.cloud.retail_v2alpha.types import catalog as gcr_catalog from google.cloud.retail_v2alpha.types import catalog_service -from .base import CatalogServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCatalogServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -494,8 +490,8 @@ class CatalogServiceRestStub: _interceptor: CatalogServiceRestInterceptor -class CatalogServiceRestTransport(CatalogServiceTransport): - """REST backend transport for CatalogService. +class CatalogServiceRestTransport(_BaseCatalogServiceRestTransport): + """REST backend synchronous transport for CatalogService. Service for managing catalog configuration. @@ -504,7 +500,6 @@ class CatalogServiceRestTransport(CatalogServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -558,21 +553,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -583,19 +569,35 @@ def __init__( self._interceptor = interceptor or CatalogServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddCatalogAttribute(CatalogServiceRestStub): + class _AddCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("AddCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.AddCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -623,47 +625,34 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_add_catalog_attribute( request, metadata ) - pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._AddCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -679,19 +668,35 @@ def __call__( resp = self._interceptor.post_add_catalog_attribute(resp) return resp - class _BatchRemoveCatalogAttributes(CatalogServiceRestStub): + class _BatchRemoveCatalogAttributes( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("BatchRemoveCatalogAttributes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.BatchRemoveCatalogAttributes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -722,47 +727,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:batchRemoveCatalogAttributes", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_http_options() + ) request, metadata = self._interceptor.pre_batch_remove_catalog_attributes( request, metadata ) - pb_request = catalog_service.BatchRemoveCatalogAttributesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._BatchRemoveCatalogAttributes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -778,19 +772,34 @@ def __call__( resp = self._interceptor.post_batch_remove_catalog_attributes(resp) return resp - class _GetAttributesConfig(CatalogServiceRestStub): + class _GetAttributesConfig( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -818,40 +827,29 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/attributesConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_attributes_config( request, metadata ) - pb_request = catalog_service.GetAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -867,19 +865,34 @@ def __call__( resp = self._interceptor.post_get_attributes_config(resp) return resp - class _GetCompletionConfig(CatalogServiceRestStub): + class _GetCompletionConfig( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -910,40 +923,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/completionConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_completion_config( request, metadata ) - pb_request = catalog_service.GetCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,9 +961,33 @@ def __call__( resp = self._interceptor.post_get_completion_config(resp) return resp - class _GetDefaultBranch(CatalogServiceRestStub): + class _GetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("GetDefaultBranch") + return hash("CatalogServiceRestTransport.GetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -990,39 +1016,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_get_default_branch( request, metadata ) - pb_request = catalog_service.GetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = CatalogServiceRestTransport._GetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1038,19 +1054,33 @@ def __call__( resp = self._interceptor.post_get_default_branch(resp) return resp - class _ListCatalogs(CatalogServiceRestStub): + class _ListCatalogs( + _BaseCatalogServiceRestTransport._BaseListCatalogs, CatalogServiceRestStub + ): def __hash__(self): - return hash("ListCatalogs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ListCatalogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1081,38 +1111,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*}/catalogs", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_http_options() + ) request, metadata = self._interceptor.pre_list_catalogs(request, metadata) - pb_request = catalog_service.ListCatalogsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._ListCatalogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1128,19 +1147,35 @@ def __call__( resp = self._interceptor.post_list_catalogs(resp) return resp - class _RemoveCatalogAttribute(CatalogServiceRestStub): + class _RemoveCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("RemoveCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.RemoveCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1168,47 +1203,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_remove_catalog_attribute( request, metadata ) - pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._RemoveCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1224,19 +1248,35 @@ def __call__( resp = self._interceptor.post_remove_catalog_attribute(resp) return resp - class _ReplaceCatalogAttribute(CatalogServiceRestStub): + class _ReplaceCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("ReplaceCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ReplaceCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1264,47 +1304,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_replace_catalog_attribute( request, metadata ) - pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._ReplaceCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1320,9 +1349,34 @@ def __call__( resp = self._interceptor.post_replace_catalog_attribute(resp) return resp - class _SetDefaultBranch(CatalogServiceRestStub): + class _SetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("SetDefaultBranch") + return hash("CatalogServiceRestTransport.SetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1345,46 +1399,34 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_set_default_branch( request, metadata ) - pb_request = catalog_service.SetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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, + response = CatalogServiceRestTransport._SetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1392,19 +1434,35 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateAttributesConfig(CatalogServiceRestStub): + class _UpdateAttributesConfig( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1432,47 +1490,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", - "body": "attributes_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_attributes_config( request, metadata ) - pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1488,19 +1535,34 @@ def __call__( resp = self._interceptor.post_update_attributes_config(resp) return resp - class _UpdateCatalog(CatalogServiceRestStub): + class _UpdateCatalog( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog, CatalogServiceRestStub + ): def __hash__(self): - return hash("UpdateCatalog") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1528,45 +1590,32 @@ def __call__( The catalog configuration. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{catalog.name=projects/*/locations/*/catalogs/*}", - "body": "catalog", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_http_options() + ) request, metadata = self._interceptor.pre_update_catalog(request, metadata) - pb_request = catalog_service.UpdateCatalogRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._UpdateCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1582,19 +1631,35 @@ def __call__( resp = self._interceptor.post_update_catalog(resp) return resp - class _UpdateCompletionConfig(CatalogServiceRestStub): + class _UpdateCompletionConfig( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1625,47 +1690,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", - "body": "completion_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_completion_config( request, metadata ) - pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1803,7 +1857,34 @@ def update_completion_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CatalogServiceRestStub): + class _GetOperation( + _BaseCatalogServiceRestTransport._BaseGetOperation, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1827,48 +1908,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1876,8 +1936,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1885,7 +1946,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CatalogServiceRestStub): + class _ListOperations( + _BaseCatalogServiceRestTransport._BaseListOperations, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1909,40 +1997,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1950,8 +2025,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest_base.py new file mode 100644 index 000000000000..06fdcb7c9523 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/catalog_service/transports/rest_base.py @@ -0,0 +1,784 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import catalog +from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +from google.cloud.retail_v2alpha.types import catalog_service + +from .base import DEFAULT_CLIENT_INFO, CatalogServiceTransport + + +class _BaseCatalogServiceRestTransport(CatalogServiceTransport): + """Base REST backend transport for CatalogService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchRemoveCatalogAttributes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:batchRemoveCatalogAttributes", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.BatchRemoveCatalogAttributesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/attributesConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/completionConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCatalogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*}/catalogs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ListCatalogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseReplaceCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.SetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", + "body": "attributes_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{catalog.name=projects/*/locations/*/catalogs/*}", + "body": "catalog", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", + "body": "completion_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCatalogServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/async_client.py index 339aa18b1fa1..d5277fdcd8b6 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/async_client.py @@ -504,11 +504,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -561,11 +557,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/client.py index b3669caf52ff..00fb289563bc 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/client.py @@ -937,11 +937,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -994,11 +990,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/README.rst new file mode 100644 index 000000000000..3f71883905ca --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CompletionServiceTransport` is the ABC for all transports. +- public child `CompletionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CompletionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCompletionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CompletionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/base.py index fb81e580b78d..6ee4e746c3de 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/base.py @@ -140,6 +140,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py index ad0f3a0811a3..299b8098fafa 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -336,21 +340,40 @@ def import_completion_data( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.complete_query: gapic_v1.method_async.wrap_method( + self.complete_query: self._wrap_method( self.complete_query, default_timeout=None, client_info=client_info, ), - self.import_completion_data: gapic_v1.method_async.wrap_method( + self.import_completion_data: self._wrap_method( self.import_completion_data, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest.py index 7f150627a406..ce5d2cce5350 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCompletionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import completion_service, import_config - -from .base import CompletionServiceTransport -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, @@ -194,8 +184,8 @@ class CompletionServiceRestStub: _interceptor: CompletionServiceRestInterceptor -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. +class CompletionServiceRestTransport(_BaseCompletionServiceRestTransport): + """REST backend synchronous transport for CompletionService. Autocomplete service for retail. @@ -208,7 +198,6 @@ class CompletionServiceRestTransport(CompletionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -262,21 +251,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -352,21 +332,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CompleteQuery(CompletionServiceRestStub): + class _CompleteQuery( + _BaseCompletionServiceRestTransport._BaseCompleteQuery, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query": "", - } - - @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 - } + return hash("CompletionServiceRestTransport.CompleteQuery") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -392,38 +385,27 @@ def __call__( Response of the autocomplete query. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_http_options() + ) request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CompletionServiceRestTransport._CompleteQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -439,19 +421,35 @@ def __call__( resp = self._interceptor.post_complete_query(resp) return resp - class _ImportCompletionData(CompletionServiceRestStub): + class _ImportCompletionData( + _BaseCompletionServiceRestTransport._BaseImportCompletionData, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("ImportCompletionData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CompletionServiceRestTransport.ImportCompletionData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -481,47 +479,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/completionData:import", - "body": "*", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_http_options() + ) request, metadata = self._interceptor.pre_import_completion_data( request, metadata ) - pb_request = import_config.ImportCompletionDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CompletionServiceRestTransport._ImportCompletionData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -560,7 +547,34 @@ def import_completion_data( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CompletionServiceRestStub): + class _GetOperation( + _BaseCompletionServiceRestTransport._BaseGetOperation, CompletionServiceRestStub + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -584,48 +598,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -633,8 +626,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -642,7 +636,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CompletionServiceRestStub): + class _ListOperations( + _BaseCompletionServiceRestTransport._BaseListOperations, + CompletionServiceRestStub, + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -666,40 +688,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -707,8 +716,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest_base.py new file mode 100644 index 000000000000..c3e1c2242130 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/completion_service/transports/rest_base.py @@ -0,0 +1,273 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO, CompletionServiceTransport + + +class _BaseCompletionServiceRestTransport(CompletionServiceTransport): + """Base REST backend transport for CompletionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCompleteQuery: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportCompletionData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/completionData:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportCompletionDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCompletionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/async_client.py index 6a65bdb49195..82ad66f96f56 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/async_client.py @@ -891,11 +891,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -948,11 +944,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/client.py index 2e7fac3245cc..01c351049d2f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/client.py @@ -1334,11 +1334,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1391,11 +1387,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/README.rst new file mode 100644 index 000000000000..ee9c627694ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ControlServiceTransport` is the ABC for all transports. +- public child `ControlServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ControlServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseControlServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ControlServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/base.py index 7ae5b25ed0a3..9fb5643ebd8a 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py index 84a0d8173e9d..851daf618229 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -395,36 +399,55 @@ def list_controls( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_control: gapic_v1.method_async.wrap_method( + self.create_control: self._wrap_method( self.create_control, default_timeout=None, client_info=client_info, ), - self.delete_control: gapic_v1.method_async.wrap_method( + self.delete_control: self._wrap_method( self.delete_control, default_timeout=None, client_info=client_info, ), - self.update_control: gapic_v1.method_async.wrap_method( + self.update_control: self._wrap_method( self.update_control, default_timeout=None, client_info=client_info, ), - self.get_control: gapic_v1.method_async.wrap_method( + self.get_control: self._wrap_method( self.get_control, default_timeout=None, client_info=client_info, ), - self.list_controls: gapic_v1.method_async.wrap_method( + self.list_controls: self._wrap_method( self.list_controls, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest.py index c601cfae2789..a6d7a6456edd 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2alpha.types import control from google.cloud.retail_v2alpha.types import control as gcr_control from google.cloud.retail_v2alpha.types import control_service -from .base import ControlServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseControlServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -263,8 +259,8 @@ class ControlServiceRestStub: _interceptor: ControlServiceRestInterceptor -class ControlServiceRestTransport(ControlServiceTransport): - """REST backend transport for ControlService. +class ControlServiceRestTransport(_BaseControlServiceRestTransport): + """REST backend synchronous transport for ControlService. Service for modifying Control. @@ -273,7 +269,6 @@ class ControlServiceRestTransport(ControlServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -327,21 +322,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -352,21 +338,34 @@ def __init__( self._interceptor = interceptor or ControlServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateControl(ControlServiceRestStub): + class _CreateControl( + _BaseControlServiceRestTransport._BaseCreateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("CreateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "controlId": "", - } - - @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 - } + return hash("ControlServiceRestTransport.CreateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -396,45 +395,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseCreateControl._get_http_options() + ) request, metadata = self._interceptor.pre_create_control(request, metadata) - pb_request = control_service.CreateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseCreateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseCreateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseCreateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._CreateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -450,19 +436,33 @@ def __call__( resp = self._interceptor.post_create_control(resp) return resp - class _DeleteControl(ControlServiceRestStub): + class _DeleteControl( + _BaseControlServiceRestTransport._BaseDeleteControl, ControlServiceRestStub + ): def __hash__(self): - return hash("DeleteControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.DeleteControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -484,38 +484,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseDeleteControl._get_http_options() + ) request, metadata = self._interceptor.pre_delete_control(request, metadata) - pb_request = control_service.DeleteControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseDeleteControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseDeleteControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._DeleteControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -523,19 +512,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetControl(ControlServiceRestStub): + class _GetControl( + _BaseControlServiceRestTransport._BaseGetControl, ControlServiceRestStub + ): def __hash__(self): - return hash("GetControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.GetControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -565,38 +568,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseGetControl._get_http_options() + ) request, metadata = self._interceptor.pre_get_control(request, metadata) - pb_request = control_service.GetControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseControlServiceRestTransport._BaseGetControl._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._GetControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -612,19 +606,33 @@ def __call__( resp = self._interceptor.post_get_control(resp) return resp - class _ListControls(ControlServiceRestStub): + class _ListControls( + _BaseControlServiceRestTransport._BaseListControls, ControlServiceRestStub + ): def __hash__(self): - return hash("ListControls") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.ListControls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -650,38 +658,27 @@ def __call__( Response for ListControls method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseListControls._get_http_options() + ) request, metadata = self._interceptor.pre_list_controls(request, metadata) - pb_request = control_service.ListControlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListControls._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseListControls._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._ListControls._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -697,19 +694,34 @@ def __call__( resp = self._interceptor.post_list_controls(resp) return resp - class _UpdateControl(ControlServiceRestStub): + class _UpdateControl( + _BaseControlServiceRestTransport._BaseUpdateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("UpdateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.UpdateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -739,45 +751,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{control.name=projects/*/locations/*/catalogs/*/controls/*}", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseUpdateControl._get_http_options() + ) request, metadata = self._interceptor.pre_update_control(request, metadata) - pb_request = control_service.UpdateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseUpdateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseUpdateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseUpdateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._UpdateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -839,7 +838,34 @@ def update_control( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ControlServiceRestStub): + class _GetOperation( + _BaseControlServiceRestTransport._BaseGetOperation, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -863,48 +889,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -912,8 +917,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -921,7 +927,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ControlServiceRestStub): + class _ListOperations( + _BaseControlServiceRestTransport._BaseListOperations, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -945,40 +978,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -986,8 +1006,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest_base.py new file mode 100644 index 000000000000..dd8a5cb59e54 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/control_service/transports/rest_base.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import control +from google.cloud.retail_v2alpha.types import control as gcr_control +from google.cloud.retail_v2alpha.types import control_service + +from .base import DEFAULT_CLIENT_INFO, ControlServiceTransport + + +class _BaseControlServiceRestTransport(ControlServiceTransport): + """Base REST backend transport for ControlService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "controlId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.CreateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseCreateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.DeleteControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseDeleteControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.GetControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseGetControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListControls: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.ListControlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseListControls._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{control.name=projects/*/locations/*/catalogs/*/controls/*}", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.UpdateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseUpdateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseControlServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/async_client.py index 52173635118b..89b7bd19a6ab 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/async_client.py @@ -962,11 +962,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1019,11 +1015,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/client.py index b37acbe562f6..2db6a0377485 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/client.py @@ -1388,11 +1388,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1445,11 +1441,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/README.rst new file mode 100644 index 000000000000..88a21803b12f --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GenerativeQuestionServiceTransport` is the ABC for all transports. +- public child `GenerativeQuestionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GenerativeQuestionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGenerativeQuestionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GenerativeQuestionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/base.py index 237bc3a91b0c..63d83db9bd43 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/grpc_asyncio.py index 8f111352796a..15e22eff4245 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -411,36 +415,55 @@ def batch_update_generative_question_configs( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.update_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.update_generative_questions_feature_config: self._wrap_method( self.update_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.get_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.get_generative_questions_feature_config: self._wrap_method( self.get_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.list_generative_question_configs: gapic_v1.method_async.wrap_method( + self.list_generative_question_configs: self._wrap_method( self.list_generative_question_configs, default_timeout=None, client_info=client_info, ), - self.update_generative_question_config: gapic_v1.method_async.wrap_method( + self.update_generative_question_config: self._wrap_method( self.update_generative_question_config, default_timeout=None, client_info=client_info, ), - self.batch_update_generative_question_configs: gapic_v1.method_async.wrap_method( + self.batch_update_generative_question_configs: self._wrap_method( self.batch_update_generative_question_configs, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest.py index 2e447751cd1c..86dca479530c 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2alpha.types import ( generative_question, generative_question_service, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import GenerativeQuestionServiceTransport +from .rest_base import _BaseGenerativeQuestionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -301,8 +297,10 @@ class GenerativeQuestionServiceRestStub: _interceptor: GenerativeQuestionServiceRestInterceptor -class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): - """REST backend transport for GenerativeQuestionService. +class GenerativeQuestionServiceRestTransport( + _BaseGenerativeQuestionServiceRestTransport +): + """REST backend synchronous transport for GenerativeQuestionService. Service for managing LLM generated questions in search serving. @@ -312,7 +310,6 @@ class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport) and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -366,21 +363,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -391,19 +379,37 @@ def __init__( self._interceptor = interceptor or GenerativeQuestionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _BatchUpdateGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _BatchUpdateGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("BatchUpdateGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.BatchUpdateGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -434,52 +440,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", - "body": "*", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_batch_update_generative_question_configs( request, metadata ) - pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._BatchUpdateGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -499,19 +490,36 @@ def __call__( resp = self._interceptor.post_batch_update_generative_question_configs(resp) return resp - class _GetGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _GetGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("GetGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.GetGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -542,45 +550,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_get_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._GetGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -596,19 +591,36 @@ def __call__( resp = self._interceptor.post_get_generative_questions_feature_config(resp) return resp - class _ListGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _ListGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("ListGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.ListGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -635,44 +647,29 @@ def __call__( Response for ListQuestions method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_generative_question_configs( request, metadata ) - pb_request = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._ListGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -692,19 +689,37 @@ def __call__( resp = self._interceptor.post_list_generative_question_configs(resp) return resp - class _UpdateGenerativeQuestionConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -734,51 +749,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", - "body": "generative_question_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_generative_question_config( request, metadata ) - pb_request = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +792,37 @@ def __call__( resp = self._interceptor.post_update_generative_question_config(resp) return resp - class _UpdateGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -837,52 +853,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - "body": "generative_questions_feature_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_update_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,7 +960,35 @@ def update_generative_questions_feature_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(GenerativeQuestionServiceRestStub): + class _GetOperation( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -983,48 +1012,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1032,8 +1042,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1041,7 +1052,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(GenerativeQuestionServiceRestStub): + class _ListOperations( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1065,40 +1104,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1106,8 +1134,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest_base.py new file mode 100644 index 000000000000..1ae4b77bf812 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/generative_question_service/transports/rest_base.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import ( + generative_question, + generative_question_service, +) + +from .base import DEFAULT_CLIENT_INFO, GenerativeQuestionServiceTransport + + +class _BaseGenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): + """Base REST backend transport for GenerativeQuestionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseBatchUpdateGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", + "body": "generative_question_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + "body": "generative_questions_feature_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseGenerativeQuestionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/async_client.py index 0780fce0cf42..b94b2042464f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/async_client.py @@ -709,11 +709,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -766,11 +762,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/client.py index 64a8db485c3e..36f13e7ae370 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/client.py @@ -1163,11 +1163,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1220,11 +1216,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/README.rst new file mode 100644 index 000000000000..61ac95a711d2 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`MerchantCenterAccountLinkServiceTransport` is the ABC for all transports. +- public child `MerchantCenterAccountLinkServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `MerchantCenterAccountLinkServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseMerchantCenterAccountLinkServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `MerchantCenterAccountLinkServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/base.py index 65867e3b3309..656f86a0368e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/base.py @@ -146,6 +146,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/grpc_asyncio.py index 34742f7f8fc9..192c96f377ef 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -370,26 +374,45 @@ def delete_merchant_center_account_link( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_merchant_center_account_links: gapic_v1.method_async.wrap_method( + self.list_merchant_center_account_links: self._wrap_method( self.list_merchant_center_account_links, default_timeout=None, client_info=client_info, ), - self.create_merchant_center_account_link: gapic_v1.method_async.wrap_method( + self.create_merchant_center_account_link: self._wrap_method( self.create_merchant_center_account_link, default_timeout=None, client_info=client_info, ), - self.delete_merchant_center_account_link: gapic_v1.method_async.wrap_method( + self.delete_merchant_center_account_link: self._wrap_method( self.delete_merchant_center_account_link, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest.py index 954e929dcc06..af9d9d9ed11f 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import merchant_center_account_link_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseMerchantCenterAccountLinkServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import merchant_center_account_link_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import MerchantCenterAccountLinkServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -222,9 +212,9 @@ class MerchantCenterAccountLinkServiceRestStub: class MerchantCenterAccountLinkServiceRestTransport( - MerchantCenterAccountLinkServiceTransport + _BaseMerchantCenterAccountLinkServiceRestTransport ): - """REST backend transport for MerchantCenterAccountLinkService. + """REST backend synchronous transport for MerchantCenterAccountLinkService. Merchant Center Link service to link a Branch to a Merchant Center Account. @@ -234,7 +224,6 @@ class MerchantCenterAccountLinkServiceRestTransport( and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -288,21 +277,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -380,19 +360,37 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateMerchantCenterAccountLink(MerchantCenterAccountLinkServiceRestStub): + class _CreateMerchantCenterAccountLink( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink, + MerchantCenterAccountLinkServiceRestStub, + ): def __hash__(self): - return hash("CreateMerchantCenterAccountLink") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "MerchantCenterAccountLinkServiceRestTransport.CreateMerchantCenterAccountLink" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -424,52 +422,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/merchantCenterAccountLinks", - "body": "merchant_center_account_link", - }, - ] + http_options = ( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_create_merchant_center_account_link( request, metadata ) - pb_request = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.pb( - request + transcoded_request = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = MerchantCenterAccountLinkServiceRestTransport._CreateMerchantCenterAccountLink._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -483,19 +466,36 @@ def __call__( resp = self._interceptor.post_create_merchant_center_account_link(resp) return resp - class _DeleteMerchantCenterAccountLink(MerchantCenterAccountLinkServiceRestStub): + class _DeleteMerchantCenterAccountLink( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseDeleteMerchantCenterAccountLink, + MerchantCenterAccountLinkServiceRestStub, + ): def __hash__(self): - return hash("DeleteMerchantCenterAccountLink") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "MerchantCenterAccountLinkServiceRestTransport.DeleteMerchantCenterAccountLink" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -520,45 +520,32 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/merchantCenterAccountLinks/*}", - }, - ] + http_options = ( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseDeleteMerchantCenterAccountLink._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_delete_merchant_center_account_link( request, metadata ) - pb_request = merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest.pb( - request + transcoded_request = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseDeleteMerchantCenterAccountLink._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseDeleteMerchantCenterAccountLink._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = MerchantCenterAccountLinkServiceRestTransport._DeleteMerchantCenterAccountLink._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -566,19 +553,36 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _ListMerchantCenterAccountLinks(MerchantCenterAccountLinkServiceRestStub): + class _ListMerchantCenterAccountLinks( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListMerchantCenterAccountLinks, + MerchantCenterAccountLinkServiceRestStub, + ): def __hash__(self): - return hash("ListMerchantCenterAccountLinks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "MerchantCenterAccountLinkServiceRestTransport.ListMerchantCenterAccountLinks" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -612,45 +616,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/merchantCenterAccountLinks", - }, - ] + http_options = ( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListMerchantCenterAccountLinks._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_list_merchant_center_account_links( request, metadata ) - pb_request = merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest.pb( - request + transcoded_request = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListMerchantCenterAccountLinks._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListMerchantCenterAccountLinks._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = MerchantCenterAccountLinkServiceRestTransport._ListMerchantCenterAccountLinks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -707,7 +698,35 @@ def list_merchant_center_account_links( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(MerchantCenterAccountLinkServiceRestStub): + class _GetOperation( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseGetOperation, + MerchantCenterAccountLinkServiceRestStub, + ): + def __hash__(self): + return hash("MerchantCenterAccountLinkServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -731,48 +750,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = MerchantCenterAccountLinkServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -780,8 +778,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -789,7 +788,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(MerchantCenterAccountLinkServiceRestStub): + class _ListOperations( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListOperations, + MerchantCenterAccountLinkServiceRestStub, + ): + def __hash__(self): + return hash("MerchantCenterAccountLinkServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -813,40 +840,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = MerchantCenterAccountLinkServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -854,8 +868,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest_base.py new file mode 100644 index 000000000000..68abca903c0b --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/merchant_center_account_link_service/transports/rest_base.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import merchant_center_account_link_service + +from .base import DEFAULT_CLIENT_INFO, MerchantCenterAccountLinkServiceTransport + + +class _BaseMerchantCenterAccountLinkServiceRestTransport( + MerchantCenterAccountLinkServiceTransport +): + """Base REST backend transport for MerchantCenterAccountLinkService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateMerchantCenterAccountLink: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/merchantCenterAccountLinks", + "body": "merchant_center_account_link", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseCreateMerchantCenterAccountLink._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMerchantCenterAccountLink: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/merchantCenterAccountLinks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseDeleteMerchantCenterAccountLink._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMerchantCenterAccountLinks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/merchantCenterAccountLinks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMerchantCenterAccountLinkServiceRestTransport._BaseListMerchantCenterAccountLinks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseMerchantCenterAccountLinkServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/async_client.py index c24d57a48936..69a82aebcbce 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/async_client.py @@ -1252,11 +1252,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1309,11 +1305,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/client.py index a066be461153..70f258c535a7 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/client.py @@ -1685,11 +1685,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1742,11 +1738,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/README.rst new file mode 100644 index 000000000000..05dddc4c34ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ModelServiceTransport` is the ABC for all transports. +- public child `ModelServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ModelServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseModelServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ModelServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/base.py index 96ae3894c2c3..0cbdec328262 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/base.py @@ -173,6 +173,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/grpc_asyncio.py index 6813ab579843..5d900fffde56 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -243,6 +244,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -490,51 +494,70 @@ def tune_model( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_model: gapic_v1.method_async.wrap_method( + self.create_model: self._wrap_method( self.create_model, default_timeout=None, client_info=client_info, ), - self.get_model: gapic_v1.method_async.wrap_method( + self.get_model: self._wrap_method( self.get_model, default_timeout=None, client_info=client_info, ), - self.pause_model: gapic_v1.method_async.wrap_method( + self.pause_model: self._wrap_method( self.pause_model, default_timeout=None, client_info=client_info, ), - self.resume_model: gapic_v1.method_async.wrap_method( + self.resume_model: self._wrap_method( self.resume_model, default_timeout=None, client_info=client_info, ), - self.delete_model: gapic_v1.method_async.wrap_method( + self.delete_model: self._wrap_method( self.delete_model, default_timeout=None, client_info=client_info, ), - self.list_models: gapic_v1.method_async.wrap_method( + self.list_models: self._wrap_method( self.list_models, default_timeout=None, client_info=client_info, ), - self.update_model: gapic_v1.method_async.wrap_method( + self.update_model: self._wrap_method( self.update_model, default_timeout=None, client_info=client_info, ), - self.tune_model: gapic_v1.method_async.wrap_method( + self.tune_model: self._wrap_method( self.tune_model, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest.py index e7b469414855..2ae8a43c6dae 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2alpha.types import model from google.cloud.retail_v2alpha.types import model as gcr_model from google.cloud.retail_v2alpha.types import model_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ModelServiceTransport +from .rest_base import _BaseModelServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -360,8 +350,8 @@ class ModelServiceRestStub: _interceptor: ModelServiceRestInterceptor -class ModelServiceRestTransport(ModelServiceTransport): - """REST backend transport for ModelService. +class ModelServiceRestTransport(_BaseModelServiceRestTransport): + """REST backend synchronous transport for ModelService. Service for performing CRUD operations on models. Recommendation models contain all the metadata necessary to generate a set of @@ -381,7 +371,6 @@ class ModelServiceRestTransport(ModelServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -435,21 +424,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -525,19 +505,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateModel(ModelServiceRestStub): + class _CreateModel( + _BaseModelServiceRestTransport._BaseCreateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("CreateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.CreateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -566,45 +561,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/models", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_http_options() + ) request, metadata = self._interceptor.pre_create_model(request, metadata) - pb_request = model_service.CreateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._CreateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -618,19 +606,33 @@ def __call__( resp = self._interceptor.post_create_model(resp) return resp - class _DeleteModel(ModelServiceRestStub): + class _DeleteModel( + _BaseModelServiceRestTransport._BaseDeleteModel, ModelServiceRestStub + ): def __hash__(self): - return hash("DeleteModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.DeleteModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -652,38 +654,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_http_options() + ) request, metadata = self._interceptor.pre_delete_model(request, metadata) - pb_request = model_service.DeleteModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._DeleteModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -691,19 +686,31 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetModel(ModelServiceRestStub): + class _GetModel(_BaseModelServiceRestTransport._BaseGetModel, ModelServiceRestStub): def __hash__(self): - return hash("GetModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.GetModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -736,38 +743,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseGetModel._get_http_options() + ) request, metadata = self._interceptor.pre_get_model(request, metadata) - pb_request = model_service.GetModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseGetModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseGetModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._GetModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -783,19 +783,33 @@ def __call__( resp = self._interceptor.post_get_model(resp) return resp - class _ListModels(ModelServiceRestStub): + class _ListModels( + _BaseModelServiceRestTransport._BaseListModels, ModelServiceRestStub + ): def __hash__(self): - return hash("ListModels") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ListModels") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -822,38 +836,31 @@ def __call__( Response to a ListModelRequest. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/models", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseListModels._get_http_options() + ) request, metadata = self._interceptor.pre_list_models(request, metadata) - pb_request = model_service.ListModelsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseListModels._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseListModels._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._ListModels._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -869,19 +876,34 @@ def __call__( resp = self._interceptor.post_list_models(resp) return resp - class _PauseModel(ModelServiceRestStub): + class _PauseModel( + _BaseModelServiceRestTransport._BasePauseModel, ModelServiceRestStub + ): def __hash__(self): - return hash("PauseModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.PauseModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -915,45 +937,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:pause", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BasePauseModel._get_http_options() + ) request, metadata = self._interceptor.pre_pause_model(request, metadata) - pb_request = model_service.PauseModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BasePauseModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BasePauseModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BasePauseModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._PauseModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -969,19 +984,34 @@ def __call__( resp = self._interceptor.post_pause_model(resp) return resp - class _ResumeModel(ModelServiceRestStub): + class _ResumeModel( + _BaseModelServiceRestTransport._BaseResumeModel, ModelServiceRestStub + ): def __hash__(self): - return hash("ResumeModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ResumeModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1015,45 +1045,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:resume", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_http_options() + ) request, metadata = self._interceptor.pre_resume_model(request, metadata) - pb_request = model_service.ResumeModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._ResumeModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1069,19 +1092,34 @@ def __call__( resp = self._interceptor.post_resume_model(resp) return resp - class _TuneModel(ModelServiceRestStub): + class _TuneModel( + _BaseModelServiceRestTransport._BaseTuneModel, ModelServiceRestStub + ): def __hash__(self): - return hash("TuneModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.TuneModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1113,45 +1151,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:tune", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_http_options() + ) request, metadata = self._interceptor.pre_tune_model(request, metadata) - pb_request = model_service.TuneModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseModelServiceRestTransport._BaseTuneModel._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._TuneModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1165,19 +1194,34 @@ def __call__( resp = self._interceptor.post_tune_model(resp) return resp - class _UpdateModel(ModelServiceRestStub): + class _UpdateModel( + _BaseModelServiceRestTransport._BaseUpdateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("UpdateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.UpdateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1211,45 +1255,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{model.name=projects/*/locations/*/catalogs/*/models/*}", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_http_options() + ) request, metadata = self._interceptor.pre_update_model(request, metadata) - pb_request = model_service.UpdateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._UpdateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1327,7 +1364,34 @@ def update_model( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ModelServiceRestStub): + class _GetOperation( + _BaseModelServiceRestTransport._BaseGetOperation, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1351,48 +1415,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ModelServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1400,8 +1445,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1409,7 +1455,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ModelServiceRestStub): + class _ListOperations( + _BaseModelServiceRestTransport._BaseListOperations, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1433,40 +1506,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseModelServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ModelServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1474,8 +1534,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest_base.py new file mode 100644 index 000000000000..14b5c1293723 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/model_service/transports/rest_base.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import model +from google.cloud.retail_v2alpha.types import model as gcr_model +from google.cloud.retail_v2alpha.types import model_service + +from .base import DEFAULT_CLIENT_INFO, ModelServiceTransport + + +class _BaseModelServiceRestTransport(ModelServiceTransport): + """Base REST backend transport for ModelService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/models", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.CreateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseCreateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.DeleteModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseDeleteModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.GetModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseGetModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListModels: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/models", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ListModelsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseListModels._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePauseModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:pause", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.PauseModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BasePauseModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseResumeModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:resume", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ResumeModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseResumeModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTuneModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/models/*}:tune", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.TuneModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseTuneModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{model.name=projects/*/locations/*/catalogs/*/models/*}", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.UpdateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseUpdateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseModelServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/async_client.py index a9f2b2c6d8cf..07fc3bc061f4 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/async_client.py @@ -377,11 +377,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -434,11 +430,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/client.py index 8006a94c516f..6bce2319b0ac 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/README.rst new file mode 100644 index 000000000000..504aaca0a144 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PredictionServiceTransport` is the ABC for all transports. +- public child `PredictionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PredictionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePredictionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PredictionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py index 2f4ade921302..c4b7c03aa4ba 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py index ef2513074d41..d4cdbcea31d4 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -272,16 +276,35 @@ def predict( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.predict: gapic_v1.method_async.wrap_method( + self.predict: self._wrap_method( self.predict, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest.py index bb5647da2f90..67fedf61500b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePredictionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import prediction_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PredictionServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -157,8 +153,8 @@ class PredictionServiceRestStub: _interceptor: PredictionServiceRestInterceptor -class PredictionServiceRestTransport(PredictionServiceTransport): - """REST backend transport for PredictionService. +class PredictionServiceRestTransport(_BasePredictionServiceRestTransport): + """REST backend synchronous transport for PredictionService. Service for making recommendation prediction. @@ -167,7 +163,6 @@ class PredictionServiceRestTransport(PredictionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -221,21 +216,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -246,19 +232,34 @@ def __init__( self._interceptor = interceptor or PredictionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Predict(PredictionServiceRestStub): + class _Predict( + _BasePredictionServiceRestTransport._BasePredict, PredictionServiceRestStub + ): def __hash__(self): - return hash("Predict") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PredictionServiceRestTransport.Predict") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -284,50 +285,36 @@ def __call__( Response message for predict method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", - "body": "*", - }, - { - "method": "post", - "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", - "body": "*", - }, - ] + http_options = ( + _BasePredictionServiceRestTransport._BasePredict._get_http_options() + ) request, metadata = self._interceptor.pre_predict(request, metadata) - pb_request = prediction_service.PredictRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePredictionServiceRestTransport._BasePredict._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BasePredictionServiceRestTransport._BasePredict._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BasePredictionServiceRestTransport._BasePredict._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PredictionServiceRestTransport._Predict._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -357,7 +344,34 @@ def predict( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(PredictionServiceRestStub): + class _GetOperation( + _BasePredictionServiceRestTransport._BaseGetOperation, PredictionServiceRestStub + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -381,48 +395,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -430,8 +423,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -439,7 +433,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(PredictionServiceRestStub): + class _ListOperations( + _BasePredictionServiceRestTransport._BaseListOperations, + PredictionServiceRestStub, + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -463,40 +485,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -504,8 +513,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest_base.py new file mode 100644 index 000000000000..2196b404adce --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/prediction_service/transports/rest_base.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO, PredictionServiceTransport + + +class _BasePredictionServiceRestTransport(PredictionServiceTransport): + """Base REST backend transport for PredictionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BasePredict: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", + "body": "*", + }, + { + "method": "post", + "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_service.PredictRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionServiceRestTransport._BasePredict._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePredictionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/async_client.py index 99bff0168e59..cb1998073ee9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/async_client.py @@ -2213,11 +2213,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2270,11 +2266,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/client.py index 1069d783b54e..3f2028d5848b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/client.py @@ -2641,11 +2641,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2698,11 +2694,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/README.rst new file mode 100644 index 000000000000..85a3f05c1f34 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProductServiceTransport` is the ABC for all transports. +- public child `ProductServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProductServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProductServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProductServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/base.py index c9edcebbfb32..181132bbee20 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/base.py @@ -209,6 +209,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py index 816ed462163a..2528eaf5b441 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -831,37 +835,37 @@ def remove_local_inventories( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_product: gapic_v1.method_async.wrap_method( + self.create_product: self._wrap_method( self.create_product, default_timeout=None, client_info=client_info, ), - self.get_product: gapic_v1.method_async.wrap_method( + self.get_product: self._wrap_method( self.get_product, default_timeout=None, client_info=client_info, ), - self.list_products: gapic_v1.method_async.wrap_method( + self.list_products: self._wrap_method( self.list_products, default_timeout=None, client_info=client_info, ), - self.update_product: gapic_v1.method_async.wrap_method( + self.update_product: self._wrap_method( self.update_product, default_timeout=None, client_info=client_info, ), - self.delete_product: gapic_v1.method_async.wrap_method( + self.delete_product: self._wrap_method( self.delete_product, default_timeout=None, client_info=client_info, ), - self.purge_products: gapic_v1.method_async.wrap_method( + self.purge_products: self._wrap_method( self.purge_products, default_timeout=None, client_info=client_info, ), - self.import_products: gapic_v1.method_async.wrap_method( + self.import_products: self._wrap_method( self.import_products, default_retry=retries.AsyncRetry( initial=0.1, @@ -876,41 +880,60 @@ def _prep_wrapped_messages(self, client_info): default_timeout=300.0, client_info=client_info, ), - self.export_products: gapic_v1.method_async.wrap_method( + self.export_products: self._wrap_method( self.export_products, default_timeout=None, client_info=client_info, ), - self.set_inventory: gapic_v1.method_async.wrap_method( + self.set_inventory: self._wrap_method( self.set_inventory, default_timeout=None, client_info=client_info, ), - self.add_fulfillment_places: gapic_v1.method_async.wrap_method( + self.add_fulfillment_places: self._wrap_method( self.add_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.remove_fulfillment_places: gapic_v1.method_async.wrap_method( + self.remove_fulfillment_places: self._wrap_method( self.remove_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.add_local_inventories: gapic_v1.method_async.wrap_method( + self.add_local_inventories: self._wrap_method( self.add_local_inventories, default_timeout=None, client_info=client_info, ), - self.remove_local_inventories: gapic_v1.method_async.wrap_method( + self.remove_local_inventories: self._wrap_method( self.remove_local_inventories, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest.py index 5467af6d9848..2a505cd27eee 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest.py @@ -16,35 +16,19 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2alpha.types import export_config, import_config from google.cloud.retail_v2alpha.types import product @@ -52,7 +36,13 @@ from google.cloud.retail_v2alpha.types import product_service, purge_config from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProductServiceTransport +from .rest_base import _BaseProductServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -522,8 +512,8 @@ class ProductServiceRestStub: _interceptor: ProductServiceRestInterceptor -class ProductServiceRestTransport(ProductServiceTransport): - """REST backend transport for ProductService. +class ProductServiceRestTransport(_BaseProductServiceRestTransport): + """REST backend synchronous transport for ProductService. Service for ingesting [Product][google.cloud.retail.v2alpha.Product] information of the customer's website. @@ -533,7 +523,6 @@ class ProductServiceRestTransport(ProductServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -587,21 +576,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -677,19 +657,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _AddFulfillmentPlaces(ProductServiceRestStub): + class _AddFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -720,47 +716,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_add_fulfillment_places( request, metadata ) - pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -774,19 +757,35 @@ def __call__( resp = self._interceptor.post_add_fulfillment_places(resp) return resp - class _AddLocalInventories(ProductServiceRestStub): + class _AddLocalInventories( + _BaseProductServiceRestTransport._BaseAddLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -817,47 +816,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_add_local_inventories( request, metadata ) - pb_request = product_service.AddLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -871,21 +857,34 @@ def __call__( resp = self._interceptor.post_add_local_inventories(resp) return resp - class _CreateProduct(ProductServiceRestStub): + class _CreateProduct( + _BaseProductServiceRestTransport._BaseCreateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("CreateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "productId": "", - } - - @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 - } + return hash("ProductServiceRestTransport.CreateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -916,45 +915,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseCreateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_create_product(request, metadata) - pb_request = product_service.CreateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseCreateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseCreateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseCreateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._CreateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -970,19 +956,33 @@ def __call__( resp = self._interceptor.post_create_product(resp) return resp - class _DeleteProduct(ProductServiceRestStub): + class _DeleteProduct( + _BaseProductServiceRestTransport._BaseDeleteProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("DeleteProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.DeleteProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1006,38 +1006,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_http_options() + ) request, metadata = self._interceptor.pre_delete_product(request, metadata) - pb_request = product_service.DeleteProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseDeleteProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseDeleteProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._DeleteProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1045,19 +1034,34 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _ExportProducts(ProductServiceRestStub): + class _ExportProducts( + _BaseProductServiceRestTransport._BaseExportProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ExportProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ExportProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1087,45 +1091,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:export", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseExportProducts._get_http_options() + ) request, metadata = self._interceptor.pre_export_products(request, metadata) - pb_request = export_config.ExportProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseExportProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseExportProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseExportProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._ExportProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1139,19 +1130,33 @@ def __call__( resp = self._interceptor.post_export_products(resp) return resp - class _GetProduct(ProductServiceRestStub): + class _GetProduct( + _BaseProductServiceRestTransport._BaseGetProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("GetProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.GetProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1182,38 +1187,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_http_options() + ) request, metadata = self._interceptor.pre_get_product(request, metadata) - pb_request = product_service.GetProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._GetProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1229,19 +1225,34 @@ def __call__( resp = self._interceptor.post_get_product(resp) return resp - class _ImportProducts(ProductServiceRestStub): + class _ImportProducts( + _BaseProductServiceRestTransport._BaseImportProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ImportProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ImportProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1270,45 +1281,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseImportProducts._get_http_options() + ) request, metadata = self._interceptor.pre_import_products(request, metadata) - pb_request = import_config.ImportProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseImportProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseImportProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseImportProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._ImportProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1322,19 +1320,33 @@ def __call__( resp = self._interceptor.post_import_products(resp) return resp - class _ListProducts(ProductServiceRestStub): + class _ListProducts( + _BaseProductServiceRestTransport._BaseListProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ListProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ListProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1365,38 +1377,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseListProducts._get_http_options() + ) request, metadata = self._interceptor.pre_list_products(request, metadata) - pb_request = product_service.ListProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListProducts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseListProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._ListProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1412,19 +1413,34 @@ def __call__( resp = self._interceptor.post_list_products(resp) return resp - class _PurgeProducts(ProductServiceRestStub): + class _PurgeProducts( + _BaseProductServiceRestTransport._BasePurgeProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("PurgeProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.PurgeProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1454,45 +1470,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BasePurgeProducts._get_http_options() + ) request, metadata = self._interceptor.pre_purge_products(request, metadata) - pb_request = purge_config.PurgeProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BasePurgeProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BasePurgeProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BasePurgeProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._PurgeProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1506,19 +1509,35 @@ def __call__( resp = self._interceptor.post_purge_products(resp) return resp - class _RemoveFulfillmentPlaces(ProductServiceRestStub): + class _RemoveFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1549,47 +1568,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_remove_fulfillment_places( request, metadata ) - pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1603,19 +1611,35 @@ def __call__( resp = self._interceptor.post_remove_fulfillment_places(resp) return resp - class _RemoveLocalInventories(ProductServiceRestStub): + class _RemoveLocalInventories( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1646,47 +1670,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_remove_local_inventories( request, metadata ) - pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1700,19 +1713,34 @@ def __call__( resp = self._interceptor.post_remove_local_inventories(resp) return resp - class _SetInventory(ProductServiceRestStub): + class _SetInventory( + _BaseProductServiceRestTransport._BaseSetInventory, ProductServiceRestStub + ): def __hash__(self): - return hash("SetInventory") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.SetInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1743,45 +1771,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseSetInventory._get_http_options() + ) request, metadata = self._interceptor.pre_set_inventory(request, metadata) - pb_request = product_service.SetInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseSetInventory._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseSetInventory._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseSetInventory._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._SetInventory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1795,19 +1810,34 @@ def __call__( resp = self._interceptor.post_set_inventory(resp) return resp - class _UpdateProduct(ProductServiceRestStub): + class _UpdateProduct( + _BaseProductServiceRestTransport._BaseUpdateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("UpdateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.UpdateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1838,45 +1868,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_update_product(request, metadata) - pb_request = product_service.UpdateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseUpdateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseUpdateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseUpdateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._UpdateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2010,7 +2027,34 @@ def update_product( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProductServiceRestStub): + class _GetOperation( + _BaseProductServiceRestTransport._BaseGetOperation, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -2034,48 +2078,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2083,8 +2106,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -2092,7 +2116,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ProductServiceRestStub): + class _ListOperations( + _BaseProductServiceRestTransport._BaseListOperations, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -2116,40 +2167,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2157,8 +2195,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest_base.py new file mode 100644 index 000000000000..e79d98b64d17 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/product_service/transports/rest_base.py @@ -0,0 +1,884 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import export_config, import_config +from google.cloud.retail_v2alpha.types import product +from google.cloud.retail_v2alpha.types import product as gcr_product +from google.cloud.retail_v2alpha.types import product_service, purge_config + +from .base import DEFAULT_CLIENT_INFO, ProductServiceTransport + + +class _BaseProductServiceRestTransport(ProductServiceTransport): + """Base REST backend transport for ProductService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseAddLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "productId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.CreateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseCreateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.DeleteProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseExportProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.GetProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseGetProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseImportProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.ListProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseListProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BasePurgeProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.SetInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseSetInventory._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.UpdateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProductServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/async_client.py index 5902a7690593..c685346acd27 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/async_client.py @@ -1221,11 +1221,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1278,11 +1274,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/client.py index 1ede1178105b..00abf8f6fce9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/client.py @@ -1649,11 +1649,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1706,11 +1702,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/README.rst new file mode 100644 index 000000000000..e8af52d6e307 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProjectServiceTransport` is the ABC for all transports. +- public child `ProjectServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProjectServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProjectServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProjectServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/base.py index 9bec6b262c7e..46b8127ac596 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/base.py @@ -172,6 +172,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/grpc_asyncio.py index efc002a861c5..d0995e7b52ad 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -503,51 +507,70 @@ def update_alert_config( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_project: gapic_v1.method_async.wrap_method( + self.get_project: self._wrap_method( self.get_project, default_timeout=None, client_info=client_info, ), - self.accept_terms: gapic_v1.method_async.wrap_method( + self.accept_terms: self._wrap_method( self.accept_terms, default_timeout=None, client_info=client_info, ), - self.enroll_solution: gapic_v1.method_async.wrap_method( + self.enroll_solution: self._wrap_method( self.enroll_solution, default_timeout=None, client_info=client_info, ), - self.list_enrolled_solutions: gapic_v1.method_async.wrap_method( + self.list_enrolled_solutions: self._wrap_method( self.list_enrolled_solutions, default_timeout=None, client_info=client_info, ), - self.get_logging_config: gapic_v1.method_async.wrap_method( + self.get_logging_config: self._wrap_method( self.get_logging_config, default_timeout=None, client_info=client_info, ), - self.update_logging_config: gapic_v1.method_async.wrap_method( + self.update_logging_config: self._wrap_method( self.update_logging_config, default_timeout=None, client_info=client_info, ), - self.get_alert_config: gapic_v1.method_async.wrap_method( + self.get_alert_config: self._wrap_method( self.get_alert_config, default_timeout=None, client_info=client_info, ), - self.update_alert_config: gapic_v1.method_async.wrap_method( + self.update_alert_config: self._wrap_method( self.update_alert_config, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest.py index b6b9897ba698..dd214dd2de8d 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest.py @@ -16,41 +16,31 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2alpha.types import project from google.cloud.retail_v2alpha.types import project as gcr_project from google.cloud.retail_v2alpha.types import project_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProjectServiceTransport +from .rest_base import _BaseProjectServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -378,8 +368,8 @@ class ProjectServiceRestStub: _interceptor: ProjectServiceRestInterceptor -class ProjectServiceRestTransport(ProjectServiceTransport): - """REST backend transport for ProjectService. +class ProjectServiceRestTransport(_BaseProjectServiceRestTransport): + """REST backend synchronous transport for ProjectService. Service for settings at Project level. @@ -388,7 +378,6 @@ class ProjectServiceRestTransport(ProjectServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -442,21 +431,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -532,19 +512,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _AcceptTerms(ProjectServiceRestStub): + class _AcceptTerms( + _BaseProjectServiceRestTransport._BaseAcceptTerms, ProjectServiceRestStub + ): def __hash__(self): - return hash("AcceptTerms") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.AcceptTerms") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -572,45 +567,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{project=projects/*/retailProject}:acceptTerms", - "body": "*", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseAcceptTerms._get_http_options() + ) request, metadata = self._interceptor.pre_accept_terms(request, metadata) - pb_request = project_service.AcceptTermsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectServiceRestTransport._BaseAcceptTerms._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectServiceRestTransport._BaseAcceptTerms._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseAcceptTerms._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectServiceRestTransport._AcceptTerms._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -626,19 +608,34 @@ def __call__( resp = self._interceptor.post_accept_terms(resp) return resp - class _EnrollSolution(ProjectServiceRestStub): + class _EnrollSolution( + _BaseProjectServiceRestTransport._BaseEnrollSolution, ProjectServiceRestStub + ): def __hash__(self): - return hash("EnrollSolution") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.EnrollSolution") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -667,45 +664,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{project=projects/*}:enrollSolution", - "body": "*", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseEnrollSolution._get_http_options() + ) request, metadata = self._interceptor.pre_enroll_solution(request, metadata) - pb_request = project_service.EnrollSolutionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectServiceRestTransport._BaseEnrollSolution._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectServiceRestTransport._BaseEnrollSolution._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseEnrollSolution._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectServiceRestTransport._EnrollSolution._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -719,19 +703,33 @@ def __call__( resp = self._interceptor.post_enroll_solution(resp) return resp - class _GetAlertConfig(ProjectServiceRestStub): + class _GetAlertConfig( + _BaseProjectServiceRestTransport._BaseGetAlertConfig, ProjectServiceRestStub + ): def __hash__(self): - return hash("GetAlertConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.GetAlertConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -759,40 +757,29 @@ def __call__( Project level alert config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/alertConfig}", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_alert_config( request, metadata ) - pb_request = project_service.GetAlertConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectServiceRestTransport._GetAlertConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -808,19 +795,33 @@ def __call__( resp = self._interceptor.post_get_alert_config(resp) return resp - class _GetLoggingConfig(ProjectServiceRestStub): + class _GetLoggingConfig( + _BaseProjectServiceRestTransport._BaseGetLoggingConfig, ProjectServiceRestStub + ): def __hash__(self): - return hash("GetLoggingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.GetLoggingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -851,40 +852,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/loggingConfig}", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseGetLoggingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_logging_config( request, metadata ) - pb_request = project_service.GetLoggingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetLoggingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseGetLoggingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectServiceRestTransport._GetLoggingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -900,19 +890,33 @@ def __call__( resp = self._interceptor.post_get_logging_config(resp) return resp - class _GetProject(ProjectServiceRestStub): + class _GetProject( + _BaseProjectServiceRestTransport._BaseGetProject, ProjectServiceRestStub + ): def __hash__(self): - return hash("GetProject") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.GetProject") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -940,38 +944,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/retailProject}", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseGetProject._get_http_options() + ) request, metadata = self._interceptor.pre_get_project(request, metadata) - pb_request = project_service.GetProjectRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetProject._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProjectServiceRestTransport._BaseGetProject._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectServiceRestTransport._GetProject._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -987,19 +982,34 @@ def __call__( resp = self._interceptor.post_get_project(resp) return resp - class _ListEnrolledSolutions(ProjectServiceRestStub): + class _ListEnrolledSolutions( + _BaseProjectServiceRestTransport._BaseListEnrolledSolutions, + ProjectServiceRestStub, + ): def __hash__(self): - return hash("ListEnrolledSolutions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.ListEnrolledSolutions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1028,40 +1038,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*}:enrolledSolutions", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseListEnrolledSolutions._get_http_options() + ) request, metadata = self._interceptor.pre_list_enrolled_solutions( request, metadata ) - pb_request = project_service.ListEnrolledSolutionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseListEnrolledSolutions._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseListEnrolledSolutions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectServiceRestTransport._ListEnrolledSolutions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1077,19 +1076,34 @@ def __call__( resp = self._interceptor.post_list_enrolled_solutions(resp) return resp - class _UpdateAlertConfig(ProjectServiceRestStub): + class _UpdateAlertConfig( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig, ProjectServiceRestStub + ): def __hash__(self): - return hash("UpdateAlertConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.UpdateAlertConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1117,47 +1131,34 @@ def __call__( Project level alert config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{alert_config.name=projects/*/alertConfig}", - "body": "alert_config", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_alert_config( request, metadata ) - pb_request = project_service.UpdateAlertConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectServiceRestTransport._UpdateAlertConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1173,19 +1174,35 @@ def __call__( resp = self._interceptor.post_update_alert_config(resp) return resp - class _UpdateLoggingConfig(ProjectServiceRestStub): + class _UpdateLoggingConfig( + _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig, + ProjectServiceRestStub, + ): def __hash__(self): - return hash("UpdateLoggingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.UpdateLoggingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1216,47 +1233,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{logging_config.name=projects/*/loggingConfig}", - "body": "logging_config", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_logging_config( request, metadata ) - pb_request = project_service.UpdateLoggingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectServiceRestTransport._UpdateLoggingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1343,7 +1347,34 @@ def update_logging_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProjectServiceRestStub): + class _GetOperation( + _BaseProjectServiceRestTransport._BaseGetOperation, ProjectServiceRestStub + ): + def __hash__(self): + return hash("ProjectServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1367,48 +1398,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseProjectServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProjectServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ProjectServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1416,8 +1426,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1425,7 +1436,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ProjectServiceRestStub): + class _ListOperations( + _BaseProjectServiceRestTransport._BaseListOperations, ProjectServiceRestStub + ): + def __hash__(self): + return hash("ProjectServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1449,40 +1487,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseProjectServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProjectServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ProjectServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1490,8 +1515,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest_base.py new file mode 100644 index 000000000000..17d3b03fcb1c --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/project_service/transports/rest_base.py @@ -0,0 +1,585 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import project +from google.cloud.retail_v2alpha.types import project as gcr_project +from google.cloud.retail_v2alpha.types import project_service + +from .base import DEFAULT_CLIENT_INFO, ProjectServiceTransport + + +class _BaseProjectServiceRestTransport(ProjectServiceTransport): + """Base REST backend transport for ProjectService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAcceptTerms: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{project=projects/*/retailProject}:acceptTerms", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.AcceptTermsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseAcceptTerms._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnrollSolution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{project=projects/*}:enrollSolution", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.EnrollSolutionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseEnrollSolution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAlertConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/alertConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.GetAlertConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLoggingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/loggingConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.GetLoggingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseGetLoggingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProject: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/retailProject}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.GetProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseGetProject._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEnrolledSolutions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*}:enrolledSolutions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.ListEnrolledSolutionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseListEnrolledSolutions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAlertConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{alert_config.name=projects/*/alertConfig}", + "body": "alert_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.UpdateAlertConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateLoggingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{logging_config.name=projects/*/loggingConfig}", + "body": "logging_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.UpdateLoggingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseUpdateLoggingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProjectServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/async_client.py index 18558f7ac7bc..ad83e3379105 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/async_client.py @@ -407,11 +407,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -464,11 +460,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/client.py index 7a75a67d124c..ecbb0909a2ac 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/client.py @@ -909,11 +909,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -966,11 +962,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/README.rst new file mode 100644 index 000000000000..8ef0891e3c25 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SearchServiceTransport` is the ABC for all transports. +- public child `SearchServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SearchServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSearchServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SearchServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/base.py index 7f40f815395b..8dbdbafde40e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py index 0446e3b46fe0..66b1a48177d6 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -279,16 +283,35 @@ def search( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.search: gapic_v1.method_async.wrap_method( + self.search: self._wrap_method( self.search, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest.py index 7c9b0c2463d2..96dc608ee8e4 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2alpha.types import search_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSearchServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2alpha.types import search_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import SearchServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -155,8 +151,8 @@ class SearchServiceRestStub: _interceptor: SearchServiceRestInterceptor -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. +class SearchServiceRestTransport(_BaseSearchServiceRestTransport): + """REST backend synchronous transport for SearchService. Service for search. @@ -169,7 +165,6 @@ class SearchServiceRestTransport(SearchServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -223,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -248,19 +234,32 @@ def __init__( self._interceptor = interceptor or SearchServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Search(SearchServiceRestStub): + class _Search(_BaseSearchServiceRestTransport._BaseSearch, SearchServiceRestStub): def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SearchServiceRestTransport.Search") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -291,50 +290,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", - "body": "*", - }, - { - "method": "post", - "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", - "body": "*", - }, - ] + http_options = ( + _BaseSearchServiceRestTransport._BaseSearch._get_http_options() + ) request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseSearchServiceRestTransport._BaseSearch._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseSearchServiceRestTransport._BaseSearch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseSearchServiceRestTransport._BaseSearch._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = SearchServiceRestTransport._Search._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -362,7 +347,34 @@ def search( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(SearchServiceRestStub): + class _GetOperation( + _BaseSearchServiceRestTransport._BaseGetOperation, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -386,48 +398,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -435,8 +426,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -444,7 +436,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(SearchServiceRestStub): + class _ListOperations( + _BaseSearchServiceRestTransport._BaseListOperations, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -468,40 +487,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -509,8 +515,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest_base.py new file mode 100644 index 000000000000..de2ce648f081 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/search_service/transports/rest_base.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import search_service + +from .base import DEFAULT_CLIENT_INFO, SearchServiceTransport + + +class _BaseSearchServiceRestTransport(SearchServiceTransport): + """Base REST backend transport for SearchService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseSearch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", + "body": "*", + }, + { + "method": "post", + "uri": "/v2alpha/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSearchServiceRestTransport._BaseSearch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSearchServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py index 2ceee2b6fbe7..457241851c43 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/async_client.py @@ -1144,11 +1144,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1201,11 +1197,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/client.py index 8279a8ab9073..6d6544409dee 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/client.py @@ -1580,11 +1580,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1637,11 +1633,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/README.rst new file mode 100644 index 000000000000..0581bb81c691 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ServingConfigServiceTransport` is the ABC for all transports. +- public child `ServingConfigServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ServingConfigServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseServingConfigServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ServingConfigServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py index 6acce8c12fbf..a724d8a44f10 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/base.py @@ -168,6 +168,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py index bc3c2bd2009b..e6b61e34d7e0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -467,46 +471,65 @@ def remove_control( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_serving_config: gapic_v1.method_async.wrap_method( + self.create_serving_config: self._wrap_method( self.create_serving_config, default_timeout=None, client_info=client_info, ), - self.delete_serving_config: gapic_v1.method_async.wrap_method( + self.delete_serving_config: self._wrap_method( self.delete_serving_config, default_timeout=None, client_info=client_info, ), - self.update_serving_config: gapic_v1.method_async.wrap_method( + self.update_serving_config: self._wrap_method( self.update_serving_config, default_timeout=None, client_info=client_info, ), - self.get_serving_config: gapic_v1.method_async.wrap_method( + self.get_serving_config: self._wrap_method( self.get_serving_config, default_timeout=None, client_info=client_info, ), - self.list_serving_configs: gapic_v1.method_async.wrap_method( + self.list_serving_configs: self._wrap_method( self.list_serving_configs, default_timeout=None, client_info=client_info, ), - self.add_control: gapic_v1.method_async.wrap_method( + self.add_control: self._wrap_method( self.add_control, default_timeout=None, client_info=client_info, ), - self.remove_control: gapic_v1.method_async.wrap_method( + self.remove_control: self._wrap_method( self.remove_control, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest.py index dca2eaeb9e9b..bf7eaea289c2 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config from google.cloud.retail_v2alpha.types import serving_config from google.cloud.retail_v2alpha.types import serving_config_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ServingConfigServiceTransport +from .rest_base import _BaseServingConfigServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -341,8 +337,8 @@ class ServingConfigServiceRestStub: _interceptor: ServingConfigServiceRestInterceptor -class ServingConfigServiceRestTransport(ServingConfigServiceTransport): - """REST backend transport for ServingConfigService. +class ServingConfigServiceRestTransport(_BaseServingConfigServiceRestTransport): + """REST backend synchronous transport for ServingConfigService. Service for modifying ServingConfig. @@ -351,7 +347,6 @@ class ServingConfigServiceRestTransport(ServingConfigServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -405,21 +400,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -430,19 +416,35 @@ def __init__( self._interceptor = interceptor or ServingConfigServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddControl(ServingConfigServiceRestStub): + class _AddControl( + _BaseServingConfigServiceRestTransport._BaseAddControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("AddControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.AddControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -472,45 +474,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_http_options() + ) request, metadata = self._interceptor.pre_add_control(request, metadata) - pb_request = serving_config_service.AddControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseAddControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseAddControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseAddControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._AddControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -526,21 +515,35 @@ def __call__( resp = self._interceptor.post_add_control(resp) return resp - class _CreateServingConfig(ServingConfigServiceRestStub): + class _CreateServingConfig( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("CreateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "servingConfigId": "", - } - - @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 - } + return hash("ServingConfigServiceRestTransport.CreateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -571,47 +574,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_create_serving_config( request, metadata ) - pb_request = serving_config_service.CreateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._CreateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -627,19 +619,34 @@ def __call__( resp = self._interceptor.post_create_serving_config(resp) return resp - class _DeleteServingConfig(ServingConfigServiceRestStub): + class _DeleteServingConfig( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("DeleteServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.DeleteServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -662,40 +669,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_delete_serving_config( request, metadata ) - pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._DeleteServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -703,19 +701,34 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetServingConfig(ServingConfigServiceRestStub): + class _GetServingConfig( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("GetServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.GetServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -745,40 +758,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_serving_config( request, metadata ) - pb_request = serving_config_service.GetServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._GetServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +798,34 @@ def __call__( resp = self._interceptor.post_get_serving_config(resp) return resp - class _ListServingConfigs(ServingConfigServiceRestStub): + class _ListServingConfigs( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("ListServingConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.ListServingConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -835,40 +854,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_serving_configs( request, metadata ) - pb_request = serving_config_service.ListServingConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._ListServingConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -884,19 +894,35 @@ def __call__( resp = self._interceptor.post_list_serving_configs(resp) return resp - class _RemoveControl(ServingConfigServiceRestStub): + class _RemoveControl( + _BaseServingConfigServiceRestTransport._BaseRemoveControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("RemoveControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.RemoveControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -926,45 +952,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_http_options() + ) request, metadata = self._interceptor.pre_remove_control(request, metadata) - pb_request = serving_config_service.RemoveControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._RemoveControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -980,19 +993,35 @@ def __call__( resp = self._interceptor.post_remove_control(resp) return resp - class _UpdateServingConfig(ServingConfigServiceRestStub): + class _UpdateServingConfig( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("UpdateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.UpdateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1023,47 +1052,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2alpha/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_serving_config( request, metadata ) - pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._UpdateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1154,7 +1172,35 @@ def update_serving_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ServingConfigServiceRestStub): + class _GetOperation( + _BaseServingConfigServiceRestTransport._BaseGetOperation, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1178,48 +1224,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1227,8 +1252,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1236,7 +1262,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ServingConfigServiceRestStub): + class _ListOperations( + _BaseServingConfigServiceRestTransport._BaseListOperations, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1260,40 +1314,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1301,8 +1342,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest_base.py new file mode 100644 index 000000000000..f9d9817e13fc --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/serving_config_service/transports/rest_base.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import serving_config as gcr_serving_config +from google.cloud.retail_v2alpha.types import serving_config +from google.cloud.retail_v2alpha.types import serving_config_service + +from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport + + +class _BaseServingConfigServiceRestTransport(ServingConfigServiceTransport): + """Base REST backend transport for ServingConfigService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.AddControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "servingConfigId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.CreateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.GetServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServingConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.ListServingConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.RemoveControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2alpha/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseServingConfigServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/async_client.py index 4c9c6fafcfc7..cbc7e4654d09 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/async_client.py @@ -968,11 +968,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1025,11 +1021,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/client.py index 5e0e66e7373f..da5b4280c2e5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/client.py @@ -1417,11 +1417,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1474,11 +1470,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/README.rst new file mode 100644 index 000000000000..45f0ef746528 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserEventServiceTransport` is the ABC for all transports. +- public child `UserEventServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserEventServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserEventServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserEventServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py index 660110bffb30..2281944800c1 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/base.py @@ -187,6 +187,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py index 8d6dc52881df..5287e873c308 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -237,6 +238,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -466,17 +470,17 @@ def rejoin_user_events( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.write_user_event: gapic_v1.method_async.wrap_method( + self.write_user_event: self._wrap_method( self.write_user_event, default_timeout=None, client_info=client_info, ), - self.collect_user_event: gapic_v1.method_async.wrap_method( + self.collect_user_event: self._wrap_method( self.collect_user_event, default_timeout=None, client_info=client_info, ), - self.purge_user_events: gapic_v1.method_async.wrap_method( + self.purge_user_events: self._wrap_method( self.purge_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -491,7 +495,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), - self.import_user_events: gapic_v1.method_async.wrap_method( + self.import_user_events: self._wrap_method( self.import_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -506,21 +510,40 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.export_user_events: gapic_v1.method_async.wrap_method( + self.export_user_events: self._wrap_method( self.export_user_events, default_timeout=None, client_info=client_info, ), - self.rejoin_user_events: gapic_v1.method_async.wrap_method( + self.rejoin_user_events: self._wrap_method( self.rejoin_user_events, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest.py index 5158149dd07e..4b2600e09e2e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest.py @@ -16,36 +16,20 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2alpha.types import ( export_config, import_config, @@ -55,7 +39,13 @@ ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import UserEventServiceTransport +from .rest_base import _BaseUserEventServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -325,8 +315,8 @@ class UserEventServiceRestStub: _interceptor: UserEventServiceRestInterceptor -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. +class UserEventServiceRestTransport(_BaseUserEventServiceRestTransport): + """REST backend synchronous transport for UserEventService. Service for ingesting end user actions on the customer website. @@ -336,7 +326,6 @@ class UserEventServiceRestTransport(UserEventServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -390,21 +379,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -480,21 +460,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CollectUserEvent(UserEventServiceRestStub): + class _CollectUserEvent( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent": "", - } - - @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 - } + return hash("UserEventServiceRestTransport.CollectUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -570,40 +563,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_collect_user_event( request, metadata ) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = UserEventServiceRestTransport._CollectUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -619,19 +601,35 @@ def __call__( resp = self._interceptor.post_collect_user_event(resp) return resp - class _ExportUserEvents(UserEventServiceRestStub): + class _ExportUserEvents( + _BaseUserEventServiceRestTransport._BaseExportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ExportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ExportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -660,47 +658,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:export", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_export_user_events( request, metadata ) - pb_request = export_config.ExportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ExportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -714,19 +699,35 @@ def __call__( resp = self._interceptor.post_export_user_events(resp) return resp - class _ImportUserEvents(UserEventServiceRestStub): + class _ImportUserEvents( + _BaseUserEventServiceRestTransport._BaseImportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ImportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -756,47 +757,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_import_user_events( request, metadata ) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ImportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -810,19 +798,35 @@ def __call__( resp = self._interceptor.post_import_user_events(resp) return resp - class _PurgeUserEvents(UserEventServiceRestStub): + class _PurgeUserEvents( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("PurgeUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.PurgeUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -852,47 +856,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_purge_user_events( request, metadata ) - pb_request = purge_config.PurgeUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._PurgeUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -906,19 +897,35 @@ def __call__( resp = self._interceptor.post_purge_user_events(resp) return resp - class _RejoinUserEvents(UserEventServiceRestStub): + class _RejoinUserEvents( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("RejoinUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.RejoinUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -948,47 +955,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_rejoin_user_events( request, metadata ) - pb_request = user_event_service.RejoinUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._RejoinUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1002,19 +996,34 @@ def __call__( resp = self._interceptor.post_rejoin_user_events(resp) return resp - class _WriteUserEvent(UserEventServiceRestStub): + class _WriteUserEvent( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent, UserEventServiceRestStub + ): def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.WriteUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1045,47 +1054,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", - "body": "user_event", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_write_user_event( request, metadata ) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._WriteUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1155,7 +1151,34 @@ def write_user_event( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(UserEventServiceRestStub): + class _GetOperation( + _BaseUserEventServiceRestTransport._BaseGetOperation, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1179,48 +1202,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1228,8 +1230,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1237,7 +1240,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(UserEventServiceRestStub): + class _ListOperations( + _BaseUserEventServiceRestTransport._BaseListOperations, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1261,40 +1291,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2alpha/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1302,8 +1319,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest_base.py new file mode 100644 index 000000000000..27cfb3167aa2 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/services/user_event_service/transports/rest_base.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2alpha.types import ( + export_config, + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + + +class _BaseUserEventServiceRestTransport(UserEventServiceTransport): + """Base REST backend transport for UserEventService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCollectUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRejoinUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.RejoinUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseWriteUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2alpha/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", + "body": "user_event", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/places/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2alpha/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseUserEventServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py index 8b80cf328714..558c8aab67c5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.22.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/async_client.py index 94be5f129a6e..4cc4d2031232 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/async_client.py @@ -403,11 +403,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -460,11 +456,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/client.py index 1ec516da60bd..e1fa9b0308de 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/README.rst new file mode 100644 index 000000000000..cf1d5125ad04 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AnalyticsServiceTransport` is the ABC for all transports. +- public child `AnalyticsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AnalyticsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAnalyticsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AnalyticsServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/base.py index 30ad39a13766..e22d329286e0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/base.py @@ -145,6 +145,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/grpc_asyncio.py index 40088411e51c..86bec7d35f74 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -295,7 +299,7 @@ def export_analytics_metrics( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.export_analytics_metrics: gapic_v1.method_async.wrap_method( + self.export_analytics_metrics: self._wrap_method( self.export_analytics_metrics, default_retry=retries.AsyncRetry( initial=0.1, @@ -310,11 +314,30 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest.py index d33a2d702194..8ef56419f775 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2beta.types import export_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAnalyticsServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2beta.types import export_config - -from .base import AnalyticsServiceTransport -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, @@ -163,8 +153,8 @@ class AnalyticsServiceRestStub: _interceptor: AnalyticsServiceRestInterceptor -class AnalyticsServiceRestTransport(AnalyticsServiceTransport): - """REST backend transport for AnalyticsService. +class AnalyticsServiceRestTransport(_BaseAnalyticsServiceRestTransport): + """REST backend synchronous transport for AnalyticsService. Service for managing & accessing retail search business metric. Retail recommendation business metric is currently not @@ -175,7 +165,6 @@ class AnalyticsServiceRestTransport(AnalyticsServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -229,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -315,19 +295,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _ExportAnalyticsMetrics(AnalyticsServiceRestStub): + class _ExportAnalyticsMetrics( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics, + AnalyticsServiceRestStub, + ): def __hash__(self): - return hash("ExportAnalyticsMetrics") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("AnalyticsServiceRestTransport.ExportAnalyticsMetrics") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -357,47 +353,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", - "body": "*", - }, - ] + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_http_options() + ) request, metadata = self._interceptor.pre_export_analytics_metrics( request, metadata ) - pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + AnalyticsServiceRestTransport._ExportAnalyticsMetrics._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -425,7 +410,34 @@ def export_analytics_metrics( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(AnalyticsServiceRestStub): + class _GetOperation( + _BaseAnalyticsServiceRestTransport._BaseGetOperation, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -449,44 +461,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -494,8 +489,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -503,7 +499,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(AnalyticsServiceRestStub): + class _ListOperations( + _BaseAnalyticsServiceRestTransport._BaseListOperations, AnalyticsServiceRestStub + ): + def __hash__(self): + return hash("AnalyticsServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -527,40 +550,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseAnalyticsServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseAnalyticsServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = AnalyticsServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -568,8 +578,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest_base.py new file mode 100644 index 000000000000..69ec98abfc0c --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/analytics_service/transports/rest_base.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import export_config + +from .base import DEFAULT_CLIENT_INFO, AnalyticsServiceTransport + + +class _BaseAnalyticsServiceRestTransport(AnalyticsServiceTransport): + """Base REST backend transport for AnalyticsService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseExportAnalyticsMetrics: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:exportAnalyticsMetrics", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportAnalyticsMetricsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAnalyticsServiceRestTransport._BaseExportAnalyticsMetrics._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAnalyticsServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/async_client.py index 91fb3daad5f8..d1a2a44e0d23 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/async_client.py @@ -1683,11 +1683,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1740,11 +1736,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/client.py index 1277c854bd5f..a3455389ce27 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/client.py @@ -2149,11 +2149,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2206,11 +2202,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/README.rst new file mode 100644 index 000000000000..c14dcbeef235 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CatalogServiceTransport` is the ABC for all transports. +- public child `CatalogServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CatalogServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCatalogServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CatalogServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/base.py index c0ea411756dd..54553a094008 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/base.py @@ -193,6 +193,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py index 20effc5c5e8d..1ff9cfae5188 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -671,71 +675,90 @@ def replace_catalog_attribute( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.list_catalogs: gapic_v1.method_async.wrap_method( + self.list_catalogs: self._wrap_method( self.list_catalogs, default_timeout=None, client_info=client_info, ), - self.update_catalog: gapic_v1.method_async.wrap_method( + self.update_catalog: self._wrap_method( self.update_catalog, default_timeout=None, client_info=client_info, ), - self.set_default_branch: gapic_v1.method_async.wrap_method( + self.set_default_branch: self._wrap_method( self.set_default_branch, default_timeout=None, client_info=client_info, ), - self.get_default_branch: gapic_v1.method_async.wrap_method( + self.get_default_branch: self._wrap_method( self.get_default_branch, default_timeout=None, client_info=client_info, ), - self.get_completion_config: gapic_v1.method_async.wrap_method( + self.get_completion_config: self._wrap_method( self.get_completion_config, default_timeout=None, client_info=client_info, ), - self.update_completion_config: gapic_v1.method_async.wrap_method( + self.update_completion_config: self._wrap_method( self.update_completion_config, default_timeout=None, client_info=client_info, ), - self.get_attributes_config: gapic_v1.method_async.wrap_method( + self.get_attributes_config: self._wrap_method( self.get_attributes_config, default_timeout=None, client_info=client_info, ), - self.update_attributes_config: gapic_v1.method_async.wrap_method( + self.update_attributes_config: self._wrap_method( self.update_attributes_config, default_timeout=None, client_info=client_info, ), - self.add_catalog_attribute: gapic_v1.method_async.wrap_method( + self.add_catalog_attribute: self._wrap_method( self.add_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.remove_catalog_attribute: gapic_v1.method_async.wrap_method( + self.remove_catalog_attribute: self._wrap_method( self.remove_catalog_attribute, default_timeout=None, client_info=client_info, ), - self.batch_remove_catalog_attributes: gapic_v1.method_async.wrap_method( + self.batch_remove_catalog_attributes: self._wrap_method( self.batch_remove_catalog_attributes, default_timeout=None, client_info=client_info, ), - self.replace_catalog_attribute: gapic_v1.method_async.wrap_method( + self.replace_catalog_attribute: self._wrap_method( self.replace_catalog_attribute, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest.py index 9437b4c1d6ff..26b3ab3ffb45 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2beta.types import catalog from google.cloud.retail_v2beta.types import catalog as gcr_catalog from google.cloud.retail_v2beta.types import catalog_service -from .base import CatalogServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCatalogServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -494,8 +490,8 @@ class CatalogServiceRestStub: _interceptor: CatalogServiceRestInterceptor -class CatalogServiceRestTransport(CatalogServiceTransport): - """REST backend transport for CatalogService. +class CatalogServiceRestTransport(_BaseCatalogServiceRestTransport): + """REST backend synchronous transport for CatalogService. Service for managing catalog configuration. @@ -504,7 +500,6 @@ class CatalogServiceRestTransport(CatalogServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -558,21 +553,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -583,19 +569,35 @@ def __init__( self._interceptor = interceptor or CatalogServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddCatalogAttribute(CatalogServiceRestStub): + class _AddCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("AddCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.AddCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -623,47 +625,34 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_add_catalog_attribute( request, metadata ) - pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._AddCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -679,19 +668,35 @@ def __call__( resp = self._interceptor.post_add_catalog_attribute(resp) return resp - class _BatchRemoveCatalogAttributes(CatalogServiceRestStub): + class _BatchRemoveCatalogAttributes( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("BatchRemoveCatalogAttributes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.BatchRemoveCatalogAttributes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -722,47 +727,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:batchRemoveCatalogAttributes", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_http_options() + ) request, metadata = self._interceptor.pre_batch_remove_catalog_attributes( request, metadata ) - pb_request = catalog_service.BatchRemoveCatalogAttributesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._BatchRemoveCatalogAttributes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -778,19 +772,34 @@ def __call__( resp = self._interceptor.post_batch_remove_catalog_attributes(resp) return resp - class _GetAttributesConfig(CatalogServiceRestStub): + class _GetAttributesConfig( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -818,40 +827,29 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/attributesConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_attributes_config( request, metadata ) - pb_request = catalog_service.GetAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -867,19 +865,34 @@ def __call__( resp = self._interceptor.post_get_attributes_config(resp) return resp - class _GetCompletionConfig(CatalogServiceRestStub): + class _GetCompletionConfig( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("GetCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.GetCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -910,40 +923,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/completionConfig}", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_completion_config( request, metadata ) - pb_request = catalog_service.GetCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._GetCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,9 +961,33 @@ def __call__( resp = self._interceptor.post_get_completion_config(resp) return resp - class _GetDefaultBranch(CatalogServiceRestStub): + class _GetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("GetDefaultBranch") + return hash("CatalogServiceRestTransport.GetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -990,39 +1016,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_get_default_branch( request, metadata ) - pb_request = catalog_service.GetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseGetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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), + response = CatalogServiceRestTransport._GetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1038,19 +1054,33 @@ def __call__( resp = self._interceptor.post_get_default_branch(resp) return resp - class _ListCatalogs(CatalogServiceRestStub): + class _ListCatalogs( + _BaseCatalogServiceRestTransport._BaseListCatalogs, CatalogServiceRestStub + ): def __hash__(self): - return hash("ListCatalogs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ListCatalogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1081,38 +1111,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*}/catalogs", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_http_options() + ) request, metadata = self._interceptor.pre_list_catalogs(request, metadata) - pb_request = catalog_service.ListCatalogsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseListCatalogs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CatalogServiceRestTransport._ListCatalogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1128,19 +1147,35 @@ def __call__( resp = self._interceptor.post_list_catalogs(resp) return resp - class _RemoveCatalogAttribute(CatalogServiceRestStub): + class _RemoveCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("RemoveCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.RemoveCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1168,47 +1203,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_remove_catalog_attribute( request, metadata ) - pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._RemoveCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1224,19 +1248,35 @@ def __call__( resp = self._interceptor.post_remove_catalog_attribute(resp) return resp - class _ReplaceCatalogAttribute(CatalogServiceRestStub): + class _ReplaceCatalogAttribute( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("ReplaceCatalogAttribute") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.ReplaceCatalogAttribute") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1264,47 +1304,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_http_options() + ) request, metadata = self._interceptor.pre_replace_catalog_attribute( request, metadata ) - pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._ReplaceCatalogAttribute._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1320,9 +1349,34 @@ def __call__( resp = self._interceptor.post_replace_catalog_attribute(resp) return resp - class _SetDefaultBranch(CatalogServiceRestStub): + class _SetDefaultBranch( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch, CatalogServiceRestStub + ): def __hash__(self): - return hash("SetDefaultBranch") + return hash("CatalogServiceRestTransport.SetDefaultBranch") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1345,46 +1399,34 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", - "body": "*", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_http_options() + ) request, metadata = self._interceptor.pre_set_default_branch( request, metadata ) - pb_request = catalog_service.SetDefaultBranchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseSetDefaultBranch._get_query_params_json( + transcoded_request ) - query_params["$alt"] = "json;enum-encoding=int" - # 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, + response = CatalogServiceRestTransport._SetDefaultBranch._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1392,19 +1434,35 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _UpdateAttributesConfig(CatalogServiceRestStub): + class _UpdateAttributesConfig( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateAttributesConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateAttributesConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1432,47 +1490,36 @@ def __call__( Catalog level attribute config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", - "body": "attributes_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_attributes_config( request, metadata ) - pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateAttributesConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1488,19 +1535,34 @@ def __call__( resp = self._interceptor.post_update_attributes_config(resp) return resp - class _UpdateCatalog(CatalogServiceRestStub): + class _UpdateCatalog( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog, CatalogServiceRestStub + ): def __hash__(self): - return hash("UpdateCatalog") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1528,45 +1590,32 @@ def __call__( The catalog configuration. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{catalog.name=projects/*/locations/*/catalogs/*}", - "body": "catalog", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_http_options() + ) request, metadata = self._interceptor.pre_update_catalog(request, metadata) - pb_request = catalog_service.UpdateCatalogRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = CatalogServiceRestTransport._UpdateCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1582,19 +1631,35 @@ def __call__( resp = self._interceptor.post_update_catalog(resp) return resp - class _UpdateCompletionConfig(CatalogServiceRestStub): + class _UpdateCompletionConfig( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig, + CatalogServiceRestStub, + ): def __hash__(self): - return hash("UpdateCompletionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CatalogServiceRestTransport.UpdateCompletionConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1625,47 +1690,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", - "body": "completion_config", - }, - ] + http_options = ( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_completion_config( request, metadata ) - pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CatalogServiceRestTransport._UpdateCompletionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1803,7 +1857,34 @@ def update_completion_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CatalogServiceRestStub): + class _GetOperation( + _BaseCatalogServiceRestTransport._BaseGetOperation, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1827,44 +1908,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1872,8 +1936,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1881,7 +1946,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CatalogServiceRestStub): + class _ListOperations( + _BaseCatalogServiceRestTransport._BaseListOperations, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1905,40 +1997,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCatalogServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCatalogServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCatalogServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CatalogServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1946,8 +2025,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest_base.py new file mode 100644 index 000000000000..0a1e1d98e302 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/catalog_service/transports/rest_base.py @@ -0,0 +1,780 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import catalog +from google.cloud.retail_v2beta.types import catalog as gcr_catalog +from google.cloud.retail_v2beta.types import catalog_service + +from .base import DEFAULT_CLIENT_INFO, CatalogServiceTransport + + +class _BaseCatalogServiceRestTransport(CatalogServiceTransport): + """Base REST backend transport for CatalogService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:addCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.AddCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseAddCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchRemoveCatalogAttributes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:batchRemoveCatalogAttributes", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.BatchRemoveCatalogAttributesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseBatchRemoveCatalogAttributes._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/attributesConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/completionConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseGetCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.GetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCatalogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*}/catalogs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ListCatalogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseListCatalogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:removeCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.RemoveCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseRemoveCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseReplaceCatalogAttribute: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{attributes_config=projects/*/locations/*/catalogs/*/attributesConfig}:replaceCatalogAttribute", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.ReplaceCatalogAttributeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseReplaceCatalogAttribute._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetDefaultBranch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.SetDefaultBranchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAttributesConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}", + "body": "attributes_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateAttributesConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateAttributesConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{catalog.name=projects/*/locations/*/catalogs/*}", + "body": "catalog", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCompletionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}", + "body": "completion_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog_service.UpdateCompletionConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCatalogServiceRestTransport._BaseUpdateCompletionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCatalogServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/async_client.py index ec78a43d06c7..1ed934a46df9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/async_client.py @@ -504,11 +504,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -561,11 +557,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/client.py index f15050a51ccb..90725e451e77 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/client.py @@ -937,11 +937,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -994,11 +990,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/README.rst new file mode 100644 index 000000000000..3f71883905ca --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CompletionServiceTransport` is the ABC for all transports. +- public child `CompletionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CompletionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCompletionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CompletionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/base.py index efbdd0114640..fe12cc51a2e1 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/base.py @@ -140,6 +140,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py index f694d73b23aa..82ba31aad692 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -233,6 +234,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -336,21 +340,40 @@ def import_completion_data( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.complete_query: gapic_v1.method_async.wrap_method( + self.complete_query: self._wrap_method( self.complete_query, default_timeout=None, client_info=client_info, ), - self.import_completion_data: gapic_v1.method_async.wrap_method( + self.import_completion_data: self._wrap_method( self.import_completion_data, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest.py index 66f103a00b2b..7effecebb7c7 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2beta.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCompletionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2beta.types import completion_service, import_config - -from .base import CompletionServiceTransport -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, @@ -194,8 +184,8 @@ class CompletionServiceRestStub: _interceptor: CompletionServiceRestInterceptor -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. +class CompletionServiceRestTransport(_BaseCompletionServiceRestTransport): + """REST backend synchronous transport for CompletionService. Autocomplete service for retail. @@ -208,7 +198,6 @@ class CompletionServiceRestTransport(CompletionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -262,21 +251,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -348,21 +328,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CompleteQuery(CompletionServiceRestStub): + class _CompleteQuery( + _BaseCompletionServiceRestTransport._BaseCompleteQuery, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query": "", - } - - @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 - } + return hash("CompletionServiceRestTransport.CompleteQuery") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -388,38 +381,27 @@ def __call__( Response of the autocomplete query. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_http_options() + ) request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = CompletionServiceRestTransport._CompleteQuery._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -435,19 +417,35 @@ def __call__( resp = self._interceptor.post_complete_query(resp) return resp - class _ImportCompletionData(CompletionServiceRestStub): + class _ImportCompletionData( + _BaseCompletionServiceRestTransport._BaseImportCompletionData, + CompletionServiceRestStub, + ): def __hash__(self): - return hash("ImportCompletionData") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("CompletionServiceRestTransport.ImportCompletionData") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -477,47 +475,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/completionData:import", - "body": "*", - }, - ] + http_options = ( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_http_options() + ) request, metadata = self._interceptor.pre_import_completion_data( request, metadata ) - pb_request = import_config.ImportCompletionDataRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + CompletionServiceRestTransport._ImportCompletionData._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -556,7 +543,34 @@ def import_completion_data( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(CompletionServiceRestStub): + class _GetOperation( + _BaseCompletionServiceRestTransport._BaseGetOperation, CompletionServiceRestStub + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -580,44 +594,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -625,8 +622,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -634,7 +632,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(CompletionServiceRestStub): + class _ListOperations( + _BaseCompletionServiceRestTransport._BaseListOperations, + CompletionServiceRestStub, + ): + def __hash__(self): + return hash("CompletionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -658,40 +684,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseCompletionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseCompletionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseCompletionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = CompletionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -699,8 +712,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest_base.py new file mode 100644 index 000000000000..f11966e71738 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/completion_service/transports/rest_base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import completion_service, import_config + +from .base import DEFAULT_CLIENT_INFO, CompletionServiceTransport + + +class _BaseCompletionServiceRestTransport(CompletionServiceTransport): + """Base REST backend transport for CompletionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCompleteQuery: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}:completeQuery", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseCompleteQuery._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportCompletionData: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/completionData:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportCompletionDataRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCompletionServiceRestTransport._BaseImportCompletionData._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCompletionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/async_client.py index 93bbec183bb9..e40e87d8c61c 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/async_client.py @@ -891,11 +891,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -948,11 +944,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/client.py index baeb546541e5..04cb33bfdedc 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/client.py @@ -1334,11 +1334,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1391,11 +1387,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/README.rst new file mode 100644 index 000000000000..ee9c627694ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ControlServiceTransport` is the ABC for all transports. +- public child `ControlServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ControlServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseControlServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ControlServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/base.py index ac69451f4028..7dd53a37a2a9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py index af298503c0f1..2f21a3f8b36c 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -395,36 +399,55 @@ def list_controls( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_control: gapic_v1.method_async.wrap_method( + self.create_control: self._wrap_method( self.create_control, default_timeout=None, client_info=client_info, ), - self.delete_control: gapic_v1.method_async.wrap_method( + self.delete_control: self._wrap_method( self.delete_control, default_timeout=None, client_info=client_info, ), - self.update_control: gapic_v1.method_async.wrap_method( + self.update_control: self._wrap_method( self.update_control, default_timeout=None, client_info=client_info, ), - self.get_control: gapic_v1.method_async.wrap_method( + self.get_control: self._wrap_method( self.get_control, default_timeout=None, client_info=client_info, ), - self.list_controls: gapic_v1.method_async.wrap_method( + self.list_controls: self._wrap_method( self.list_controls, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest.py index 5cad82cce71b..61092164027b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2beta.types import control from google.cloud.retail_v2beta.types import control as gcr_control from google.cloud.retail_v2beta.types import control_service -from .base import ControlServiceTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseControlServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -263,8 +259,8 @@ class ControlServiceRestStub: _interceptor: ControlServiceRestInterceptor -class ControlServiceRestTransport(ControlServiceTransport): - """REST backend transport for ControlService. +class ControlServiceRestTransport(_BaseControlServiceRestTransport): + """REST backend synchronous transport for ControlService. Service for modifying Control. @@ -273,7 +269,6 @@ class ControlServiceRestTransport(ControlServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -327,21 +322,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -352,21 +338,34 @@ def __init__( self._interceptor = interceptor or ControlServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateControl(ControlServiceRestStub): + class _CreateControl( + _BaseControlServiceRestTransport._BaseCreateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("CreateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "controlId": "", - } - - @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 - } + return hash("ControlServiceRestTransport.CreateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -396,45 +395,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseCreateControl._get_http_options() + ) request, metadata = self._interceptor.pre_create_control(request, metadata) - pb_request = control_service.CreateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseCreateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseCreateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseCreateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._CreateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -450,19 +436,33 @@ def __call__( resp = self._interceptor.post_create_control(resp) return resp - class _DeleteControl(ControlServiceRestStub): + class _DeleteControl( + _BaseControlServiceRestTransport._BaseDeleteControl, ControlServiceRestStub + ): def __hash__(self): - return hash("DeleteControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.DeleteControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -484,38 +484,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseDeleteControl._get_http_options() + ) request, metadata = self._interceptor.pre_delete_control(request, metadata) - pb_request = control_service.DeleteControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseDeleteControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseDeleteControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._DeleteControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -523,19 +512,33 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetControl(ControlServiceRestStub): + class _GetControl( + _BaseControlServiceRestTransport._BaseGetControl, ControlServiceRestStub + ): def __hash__(self): - return hash("GetControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.GetControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -565,38 +568,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseGetControl._get_http_options() + ) request, metadata = self._interceptor.pre_get_control(request, metadata) - pb_request = control_service.GetControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetControl._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseControlServiceRestTransport._BaseGetControl._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._GetControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -612,19 +606,33 @@ def __call__( resp = self._interceptor.post_get_control(resp) return resp - class _ListControls(ControlServiceRestStub): + class _ListControls( + _BaseControlServiceRestTransport._BaseListControls, ControlServiceRestStub + ): def __hash__(self): - return hash("ListControls") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.ListControls") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -650,38 +658,27 @@ def __call__( Response for ListControls method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseListControls._get_http_options() + ) request, metadata = self._interceptor.pre_list_controls(request, metadata) - pb_request = control_service.ListControlsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListControls._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseListControls._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ControlServiceRestTransport._ListControls._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -697,19 +694,34 @@ def __call__( resp = self._interceptor.post_list_controls(resp) return resp - class _UpdateControl(ControlServiceRestStub): + class _UpdateControl( + _BaseControlServiceRestTransport._BaseUpdateControl, ControlServiceRestStub + ): def __hash__(self): - return hash("UpdateControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ControlServiceRestTransport.UpdateControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -739,45 +751,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{control.name=projects/*/locations/*/catalogs/*/controls/*}", - "body": "control", - }, - ] + http_options = ( + _BaseControlServiceRestTransport._BaseUpdateControl._get_http_options() + ) request, metadata = self._interceptor.pre_update_control(request, metadata) - pb_request = control_service.UpdateControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseControlServiceRestTransport._BaseUpdateControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseControlServiceRestTransport._BaseUpdateControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseControlServiceRestTransport._BaseUpdateControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ControlServiceRestTransport._UpdateControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -839,7 +838,34 @@ def update_control( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ControlServiceRestStub): + class _GetOperation( + _BaseControlServiceRestTransport._BaseGetOperation, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -863,44 +889,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -908,8 +917,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -917,7 +927,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ControlServiceRestStub): + class _ListOperations( + _BaseControlServiceRestTransport._BaseListOperations, ControlServiceRestStub + ): + def __hash__(self): + return hash("ControlServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -941,40 +978,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseControlServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseControlServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseControlServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ControlServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -982,8 +1006,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest_base.py new file mode 100644 index 000000000000..7faa6d4db9ce --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/control_service/transports/rest_base.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import control +from google.cloud.retail_v2beta.types import control as gcr_control +from google.cloud.retail_v2beta.types import control_service + +from .base import DEFAULT_CLIENT_INFO, ControlServiceTransport + + +class _BaseControlServiceRestTransport(ControlServiceTransport): + """Base REST backend transport for ControlService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "controlId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.CreateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseCreateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.DeleteControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseDeleteControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.GetControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseGetControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListControls: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.ListControlsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseListControls._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{control.name=projects/*/locations/*/catalogs/*/controls/*}", + "body": "control", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = control_service.UpdateControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseControlServiceRestTransport._BaseUpdateControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseControlServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/async_client.py index 1204a43395cc..8dbdb4bb0955 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/async_client.py @@ -962,11 +962,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1019,11 +1015,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/client.py index c8d7b019c8ea..b672d46871a0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/client.py @@ -1388,11 +1388,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1445,11 +1441,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/README.rst new file mode 100644 index 000000000000..88a21803b12f --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GenerativeQuestionServiceTransport` is the ABC for all transports. +- public child `GenerativeQuestionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GenerativeQuestionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGenerativeQuestionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GenerativeQuestionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/base.py index 9a967141097c..56c2c366d8ad 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/base.py @@ -158,6 +158,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/grpc_asyncio.py index df68cc1d710e..6e291068347e 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -411,36 +415,55 @@ def batch_update_generative_question_configs( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.update_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.update_generative_questions_feature_config: self._wrap_method( self.update_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.get_generative_questions_feature_config: gapic_v1.method_async.wrap_method( + self.get_generative_questions_feature_config: self._wrap_method( self.get_generative_questions_feature_config, default_timeout=None, client_info=client_info, ), - self.list_generative_question_configs: gapic_v1.method_async.wrap_method( + self.list_generative_question_configs: self._wrap_method( self.list_generative_question_configs, default_timeout=None, client_info=client_info, ), - self.update_generative_question_config: gapic_v1.method_async.wrap_method( + self.update_generative_question_config: self._wrap_method( self.update_generative_question_config, default_timeout=None, client_info=client_info, ), - self.batch_update_generative_question_configs: gapic_v1.method_async.wrap_method( + self.batch_update_generative_question_configs: self._wrap_method( self.batch_update_generative_question_configs, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest.py index 4c9d37fb0766..e061a74627b0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2beta.types import ( generative_question, generative_question_service, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import GenerativeQuestionServiceTransport +from .rest_base import _BaseGenerativeQuestionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -301,8 +297,10 @@ class GenerativeQuestionServiceRestStub: _interceptor: GenerativeQuestionServiceRestInterceptor -class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): - """REST backend transport for GenerativeQuestionService. +class GenerativeQuestionServiceRestTransport( + _BaseGenerativeQuestionServiceRestTransport +): + """REST backend synchronous transport for GenerativeQuestionService. Service for managing LLM generated questions in search serving. @@ -312,7 +310,6 @@ class GenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport) and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -366,21 +363,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -391,19 +379,37 @@ def __init__( self._interceptor = interceptor or GenerativeQuestionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _BatchUpdateGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _BatchUpdateGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("BatchUpdateGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.BatchUpdateGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -434,52 +440,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", - "body": "*", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_batch_update_generative_question_configs( request, metadata ) - pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._BatchUpdateGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -499,19 +490,36 @@ def __call__( resp = self._interceptor.post_batch_update_generative_question_configs(resp) return resp - class _GetGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _GetGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("GetGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.GetGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -542,45 +550,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_get_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._GetGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -596,19 +591,36 @@ def __call__( resp = self._interceptor.post_get_generative_questions_feature_config(resp) return resp - class _ListGenerativeQuestionConfigs(GenerativeQuestionServiceRestStub): + class _ListGenerativeQuestionConfigs( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("ListGenerativeQuestionConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.ListGenerativeQuestionConfigs" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -635,44 +647,29 @@ def __call__( Response for ListQuestions method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_generative_question_configs( request, metadata ) - pb_request = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_transcoded_request( + http_options, 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"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = GenerativeQuestionServiceRestTransport._ListGenerativeQuestionConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -692,19 +689,37 @@ def __call__( resp = self._interceptor.post_list_generative_question_configs(resp) return resp - class _UpdateGenerativeQuestionConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -734,51 +749,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", - "body": "generative_question_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_generative_question_config( request, metadata ) - pb_request = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - request - ) + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +792,37 @@ def __call__( resp = self._interceptor.post_update_generative_question_config(resp) return resp - class _UpdateGenerativeQuestionsFeatureConfig(GenerativeQuestionServiceRestStub): + class _UpdateGenerativeQuestionsFeatureConfig( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig, + GenerativeQuestionServiceRestStub, + ): def __hash__(self): - return hash("UpdateGenerativeQuestionsFeatureConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + return hash( + "GenerativeQuestionServiceRestTransport.UpdateGenerativeQuestionsFeatureConfig" + ) - @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 - } + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -837,52 +853,37 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", - "body": "generative_questions_feature_config", - }, - ] + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_http_options() + ) ( request, metadata, ) = self._interceptor.pre_update_generative_questions_feature_config( request, metadata ) - pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - request + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_transcoded_request( + http_options, request ) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = GenerativeQuestionServiceRestTransport._UpdateGenerativeQuestionsFeatureConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,7 +960,35 @@ def update_generative_questions_feature_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(GenerativeQuestionServiceRestStub): + class _GetOperation( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -983,44 +1012,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1028,8 +1042,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1037,7 +1052,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(GenerativeQuestionServiceRestStub): + class _ListOperations( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations, + GenerativeQuestionServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeQuestionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1061,40 +1104,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseGenerativeQuestionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ( + GenerativeQuestionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1102,8 +1134,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest_base.py new file mode 100644 index 000000000000..2f35e096c0ec --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/generative_question_service/transports/rest_base.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import ( + generative_question, + generative_question_service, +) + +from .base import DEFAULT_CLIENT_INFO, GenerativeQuestionServiceTransport + + +class _BaseGenerativeQuestionServiceRestTransport(GenerativeQuestionServiceTransport): + """Base REST backend transport for GenerativeQuestionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseBatchUpdateGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/generativeQuestion:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseBatchUpdateGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseGetGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGenerativeQuestionConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/generativeQuestions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseListGenerativeQuestionConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{generative_question_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestion", + "body": "generative_question_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGenerativeQuestionsFeatureConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{generative_questions_feature_config.catalog=projects/*/locations/*/catalogs/*}/generativeQuestionFeature", + "body": "generative_questions_feature_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeQuestionServiceRestTransport._BaseUpdateGenerativeQuestionsFeatureConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseGenerativeQuestionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/async_client.py index 338ec4548803..9fca2c05572d 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/async_client.py @@ -1246,11 +1246,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1303,11 +1299,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/client.py index ce03a15c002b..9fa345180dd5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/client.py @@ -1679,11 +1679,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1736,11 +1732,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/README.rst new file mode 100644 index 000000000000..05dddc4c34ad --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ModelServiceTransport` is the ABC for all transports. +- public child `ModelServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ModelServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseModelServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ModelServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/base.py index c74aa4d53536..8b808de589e7 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/base.py @@ -173,6 +173,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/grpc_asyncio.py index 03525873f21b..4cc90cf97503 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -243,6 +244,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -490,51 +494,70 @@ def tune_model( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_model: gapic_v1.method_async.wrap_method( + self.create_model: self._wrap_method( self.create_model, default_timeout=None, client_info=client_info, ), - self.get_model: gapic_v1.method_async.wrap_method( + self.get_model: self._wrap_method( self.get_model, default_timeout=None, client_info=client_info, ), - self.pause_model: gapic_v1.method_async.wrap_method( + self.pause_model: self._wrap_method( self.pause_model, default_timeout=None, client_info=client_info, ), - self.resume_model: gapic_v1.method_async.wrap_method( + self.resume_model: self._wrap_method( self.resume_model, default_timeout=None, client_info=client_info, ), - self.delete_model: gapic_v1.method_async.wrap_method( + self.delete_model: self._wrap_method( self.delete_model, default_timeout=None, client_info=client_info, ), - self.list_models: gapic_v1.method_async.wrap_method( + self.list_models: self._wrap_method( self.list_models, default_timeout=None, client_info=client_info, ), - self.update_model: gapic_v1.method_async.wrap_method( + self.update_model: self._wrap_method( self.update_model, default_timeout=None, client_info=client_info, ), - self.tune_model: gapic_v1.method_async.wrap_method( + self.tune_model: self._wrap_method( self.tune_model, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest.py index a754de7df076..9144cc409c99 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2beta.types import model from google.cloud.retail_v2beta.types import model as gcr_model from google.cloud.retail_v2beta.types import model_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ModelServiceTransport +from .rest_base import _BaseModelServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -360,8 +350,8 @@ class ModelServiceRestStub: _interceptor: ModelServiceRestInterceptor -class ModelServiceRestTransport(ModelServiceTransport): - """REST backend transport for ModelService. +class ModelServiceRestTransport(_BaseModelServiceRestTransport): + """REST backend synchronous transport for ModelService. Service for performing CRUD operations on models. Recommendation models contain all the metadata necessary to generate a set of @@ -381,7 +371,6 @@ class ModelServiceRestTransport(ModelServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -435,21 +424,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -521,19 +501,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateModel(ModelServiceRestStub): + class _CreateModel( + _BaseModelServiceRestTransport._BaseCreateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("CreateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.CreateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -562,45 +557,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/models", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_http_options() + ) request, metadata = self._interceptor.pre_create_model(request, metadata) - pb_request = model_service.CreateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseCreateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._CreateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -614,19 +602,33 @@ def __call__( resp = self._interceptor.post_create_model(resp) return resp - class _DeleteModel(ModelServiceRestStub): + class _DeleteModel( + _BaseModelServiceRestTransport._BaseDeleteModel, ModelServiceRestStub + ): def __hash__(self): - return hash("DeleteModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.DeleteModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -648,38 +650,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_http_options() + ) request, metadata = self._interceptor.pre_delete_model(request, metadata) - pb_request = model_service.DeleteModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseDeleteModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._DeleteModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -687,19 +682,31 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetModel(ModelServiceRestStub): + class _GetModel(_BaseModelServiceRestTransport._BaseGetModel, ModelServiceRestStub): def __hash__(self): - return hash("GetModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.GetModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -732,38 +739,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseGetModel._get_http_options() + ) request, metadata = self._interceptor.pre_get_model(request, metadata) - pb_request = model_service.GetModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseGetModel._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseGetModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._GetModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -779,19 +779,33 @@ def __call__( resp = self._interceptor.post_get_model(resp) return resp - class _ListModels(ModelServiceRestStub): + class _ListModels( + _BaseModelServiceRestTransport._BaseListModels, ModelServiceRestStub + ): def __hash__(self): - return hash("ListModels") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ListModels") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -818,38 +832,31 @@ def __call__( Response to a ListModelRequest. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/models", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseListModels._get_http_options() + ) request, metadata = self._interceptor.pre_list_models(request, metadata) - pb_request = model_service.ListModelsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseModelServiceRestTransport._BaseListModels._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseListModels._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ModelServiceRestTransport._ListModels._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -865,19 +872,34 @@ def __call__( resp = self._interceptor.post_list_models(resp) return resp - class _PauseModel(ModelServiceRestStub): + class _PauseModel( + _BaseModelServiceRestTransport._BasePauseModel, ModelServiceRestStub + ): def __hash__(self): - return hash("PauseModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.PauseModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -911,45 +933,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:pause", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BasePauseModel._get_http_options() + ) request, metadata = self._interceptor.pre_pause_model(request, metadata) - pb_request = model_service.PauseModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BasePauseModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BasePauseModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BasePauseModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._PauseModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -965,19 +980,34 @@ def __call__( resp = self._interceptor.post_pause_model(resp) return resp - class _ResumeModel(ModelServiceRestStub): + class _ResumeModel( + _BaseModelServiceRestTransport._BaseResumeModel, ModelServiceRestStub + ): def __hash__(self): - return hash("ResumeModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.ResumeModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1011,45 +1041,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:resume", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_http_options() + ) request, metadata = self._interceptor.pre_resume_model(request, metadata) - pb_request = model_service.ResumeModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseResumeModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._ResumeModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1065,19 +1088,34 @@ def __call__( resp = self._interceptor.post_resume_model(resp) return resp - class _TuneModel(ModelServiceRestStub): + class _TuneModel( + _BaseModelServiceRestTransport._BaseTuneModel, ModelServiceRestStub + ): def __hash__(self): - return hash("TuneModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.TuneModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1109,45 +1147,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:tune", - "body": "*", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_http_options() + ) request, metadata = self._interceptor.pre_tune_model(request, metadata) - pb_request = model_service.TuneModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseModelServiceRestTransport._BaseTuneModel._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseTuneModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._TuneModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1161,19 +1190,34 @@ def __call__( resp = self._interceptor.post_tune_model(resp) return resp - class _UpdateModel(ModelServiceRestStub): + class _UpdateModel( + _BaseModelServiceRestTransport._BaseUpdateModel, ModelServiceRestStub + ): def __hash__(self): - return hash("UpdateModel") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ModelServiceRestTransport.UpdateModel") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1207,45 +1251,38 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{model.name=projects/*/locations/*/catalogs/*/models/*}", - "body": "model", - }, - ] + http_options = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_http_options() + ) request, metadata = self._interceptor.pre_update_model(request, metadata) - pb_request = model_service.UpdateModelRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseModelServiceRestTransport._BaseUpdateModel._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ModelServiceRestTransport._UpdateModel._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1323,7 +1360,34 @@ def update_model( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ModelServiceRestStub): + class _GetOperation( + _BaseModelServiceRestTransport._BaseGetOperation, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1347,44 +1411,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseModelServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ModelServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1392,8 +1441,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1401,7 +1451,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ModelServiceRestStub): + class _ListOperations( + _BaseModelServiceRestTransport._BaseListOperations, ModelServiceRestStub + ): + def __hash__(self): + return hash("ModelServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1425,40 +1502,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseModelServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseModelServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseModelServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ModelServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1466,8 +1530,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest_base.py new file mode 100644 index 000000000000..498d106139a1 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/model_service/transports/rest_base.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import model +from google.cloud.retail_v2beta.types import model as gcr_model +from google.cloud.retail_v2beta.types import model_service + +from .base import DEFAULT_CLIENT_INFO, ModelServiceTransport + + +class _BaseModelServiceRestTransport(ModelServiceTransport): + """Base REST backend transport for ModelService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/models", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.CreateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseCreateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.DeleteModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseDeleteModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.GetModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseGetModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListModels: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/models", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ListModelsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseListModels._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePauseModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:pause", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.PauseModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BasePauseModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseResumeModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:resume", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.ResumeModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseResumeModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTuneModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/models/*}:tune", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.TuneModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseTuneModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateModel: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{model.name=projects/*/locations/*/catalogs/*/models/*}", + "body": "model", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = model_service.UpdateModelRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseModelServiceRestTransport._BaseUpdateModel._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseModelServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/async_client.py index 789d08a4d009..b72c49a335e3 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/async_client.py @@ -377,11 +377,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -434,11 +430,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/client.py index f36033352de5..84ac2f2527ec 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/client.py @@ -818,11 +818,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -875,11 +871,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/README.rst new file mode 100644 index 000000000000..504aaca0a144 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`PredictionServiceTransport` is the ABC for all transports. +- public child `PredictionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `PredictionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BasePredictionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `PredictionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/base.py index deac4e7c8c96..b7fdc7c83ac9 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py index 7df89cfc7fff..8843a32c7205 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -272,16 +276,35 @@ def predict( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.predict: gapic_v1.method_async.wrap_method( + self.predict: self._wrap_method( self.predict, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest.py index 0d878f1d5072..132d2f4dda64 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2beta.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePredictionServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2beta.types import prediction_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import PredictionServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -157,8 +153,8 @@ class PredictionServiceRestStub: _interceptor: PredictionServiceRestInterceptor -class PredictionServiceRestTransport(PredictionServiceTransport): - """REST backend transport for PredictionService. +class PredictionServiceRestTransport(_BasePredictionServiceRestTransport): + """REST backend synchronous transport for PredictionService. Service for making recommendation prediction. @@ -167,7 +163,6 @@ class PredictionServiceRestTransport(PredictionServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -221,21 +216,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -246,19 +232,34 @@ def __init__( self._interceptor = interceptor or PredictionServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Predict(PredictionServiceRestStub): + class _Predict( + _BasePredictionServiceRestTransport._BasePredict, PredictionServiceRestStub + ): def __hash__(self): - return hash("Predict") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("PredictionServiceRestTransport.Predict") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -284,50 +285,36 @@ def __call__( Response message for predict method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", - "body": "*", - }, - { - "method": "post", - "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", - "body": "*", - }, - ] + http_options = ( + _BasePredictionServiceRestTransport._BasePredict._get_http_options() + ) request, metadata = self._interceptor.pre_predict(request, metadata) - pb_request = prediction_service.PredictRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BasePredictionServiceRestTransport._BasePredict._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BasePredictionServiceRestTransport._BasePredict._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BasePredictionServiceRestTransport._BasePredict._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = PredictionServiceRestTransport._Predict._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -357,7 +344,34 @@ def predict( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(PredictionServiceRestStub): + class _GetOperation( + _BasePredictionServiceRestTransport._BaseGetOperation, PredictionServiceRestStub + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -381,44 +395,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -426,8 +423,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -435,7 +433,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(PredictionServiceRestStub): + class _ListOperations( + _BasePredictionServiceRestTransport._BaseListOperations, + PredictionServiceRestStub, + ): + def __hash__(self): + return hash("PredictionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -459,40 +485,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BasePredictionServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BasePredictionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BasePredictionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = PredictionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -500,8 +513,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest_base.py new file mode 100644 index 000000000000..d1b6f27ecd3f --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/prediction_service/transports/rest_base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import prediction_service + +from .base import DEFAULT_CLIENT_INFO, PredictionServiceTransport + + +class _BasePredictionServiceRestTransport(PredictionServiceTransport): + """Base REST backend transport for PredictionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BasePredict: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/placements/*}:predict", + "body": "*", + }, + { + "method": "post", + "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:predict", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = prediction_service.PredictRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePredictionServiceRestTransport._BasePredict._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePredictionServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/async_client.py index 017ddd600ec6..dd1d99d714e1 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/async_client.py @@ -2210,11 +2210,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2267,11 +2263,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/client.py index 2962e1a264c0..31bbb846dab0 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/client.py @@ -2638,11 +2638,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2695,11 +2691,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/README.rst new file mode 100644 index 000000000000..85a3f05c1f34 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProductServiceTransport` is the ABC for all transports. +- public child `ProductServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProductServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProductServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProductServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/base.py index e9bced2f92d2..69c363455e98 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/base.py @@ -209,6 +209,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py index 12a79e862403..601f7966eb48 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -234,6 +235,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -830,37 +834,37 @@ def remove_local_inventories( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_product: gapic_v1.method_async.wrap_method( + self.create_product: self._wrap_method( self.create_product, default_timeout=None, client_info=client_info, ), - self.get_product: gapic_v1.method_async.wrap_method( + self.get_product: self._wrap_method( self.get_product, default_timeout=None, client_info=client_info, ), - self.list_products: gapic_v1.method_async.wrap_method( + self.list_products: self._wrap_method( self.list_products, default_timeout=None, client_info=client_info, ), - self.update_product: gapic_v1.method_async.wrap_method( + self.update_product: self._wrap_method( self.update_product, default_timeout=None, client_info=client_info, ), - self.delete_product: gapic_v1.method_async.wrap_method( + self.delete_product: self._wrap_method( self.delete_product, default_timeout=None, client_info=client_info, ), - self.purge_products: gapic_v1.method_async.wrap_method( + self.purge_products: self._wrap_method( self.purge_products, default_timeout=None, client_info=client_info, ), - self.import_products: gapic_v1.method_async.wrap_method( + self.import_products: self._wrap_method( self.import_products, default_retry=retries.AsyncRetry( initial=0.1, @@ -875,41 +879,60 @@ def _prep_wrapped_messages(self, client_info): default_timeout=300.0, client_info=client_info, ), - self.export_products: gapic_v1.method_async.wrap_method( + self.export_products: self._wrap_method( self.export_products, default_timeout=None, client_info=client_info, ), - self.set_inventory: gapic_v1.method_async.wrap_method( + self.set_inventory: self._wrap_method( self.set_inventory, default_timeout=None, client_info=client_info, ), - self.add_fulfillment_places: gapic_v1.method_async.wrap_method( + self.add_fulfillment_places: self._wrap_method( self.add_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.remove_fulfillment_places: gapic_v1.method_async.wrap_method( + self.remove_fulfillment_places: self._wrap_method( self.remove_fulfillment_places, default_timeout=None, client_info=client_info, ), - self.add_local_inventories: gapic_v1.method_async.wrap_method( + self.add_local_inventories: self._wrap_method( self.add_local_inventories, default_timeout=None, client_info=client_info, ), - self.remove_local_inventories: gapic_v1.method_async.wrap_method( + self.remove_local_inventories: self._wrap_method( self.remove_local_inventories, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest.py index ca1e9a50d73b..68943510d197 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest.py @@ -16,35 +16,19 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2beta.types import export_config, import_config from google.cloud.retail_v2beta.types import product @@ -52,7 +36,13 @@ from google.cloud.retail_v2beta.types import product_service, purge_config from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProductServiceTransport +from .rest_base import _BaseProductServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -522,8 +512,8 @@ class ProductServiceRestStub: _interceptor: ProductServiceRestInterceptor -class ProductServiceRestTransport(ProductServiceTransport): - """REST backend transport for ProductService. +class ProductServiceRestTransport(_BaseProductServiceRestTransport): + """REST backend synchronous transport for ProductService. Service for ingesting [Product][google.cloud.retail.v2beta.Product] information of the customer's website. @@ -533,7 +523,6 @@ class ProductServiceRestTransport(ProductServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -587,21 +576,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -673,19 +653,35 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _AddFulfillmentPlaces(ProductServiceRestStub): + class _AddFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -716,47 +712,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_add_fulfillment_places( request, metadata ) - pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -770,19 +753,35 @@ def __call__( resp = self._interceptor.post_add_fulfillment_places(resp) return resp - class _AddLocalInventories(ProductServiceRestStub): + class _AddLocalInventories( + _BaseProductServiceRestTransport._BaseAddLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("AddLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.AddLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -813,47 +812,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_add_local_inventories( request, metadata ) - pb_request = product_service.AddLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseAddLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._AddLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -867,21 +853,34 @@ def __call__( resp = self._interceptor.post_add_local_inventories(resp) return resp - class _CreateProduct(ProductServiceRestStub): + class _CreateProduct( + _BaseProductServiceRestTransport._BaseCreateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("CreateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "productId": "", - } - - @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 - } + return hash("ProductServiceRestTransport.CreateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -912,45 +911,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseCreateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_create_product(request, metadata) - pb_request = product_service.CreateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseCreateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseCreateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseCreateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._CreateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -966,19 +952,33 @@ def __call__( resp = self._interceptor.post_create_product(resp) return resp - class _DeleteProduct(ProductServiceRestStub): + class _DeleteProduct( + _BaseProductServiceRestTransport._BaseDeleteProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("DeleteProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.DeleteProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1002,38 +1002,27 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_http_options() + ) request, metadata = self._interceptor.pre_delete_product(request, metadata) - pb_request = product_service.DeleteProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseDeleteProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseDeleteProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._DeleteProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1041,19 +1030,34 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _ExportProducts(ProductServiceRestStub): + class _ExportProducts( + _BaseProductServiceRestTransport._BaseExportProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ExportProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ExportProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1083,45 +1087,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:export", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseExportProducts._get_http_options() + ) request, metadata = self._interceptor.pre_export_products(request, metadata) - pb_request = export_config.ExportProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseExportProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseExportProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseExportProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._ExportProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1135,19 +1126,33 @@ def __call__( resp = self._interceptor.post_export_products(resp) return resp - class _GetProduct(ProductServiceRestStub): + class _GetProduct( + _BaseProductServiceRestTransport._BaseGetProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("GetProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.GetProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1178,38 +1183,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_http_options() + ) request, metadata = self._interceptor.pre_get_product(request, metadata) - pb_request = product_service.GetProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetProduct._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseProductServiceRestTransport._BaseGetProduct._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._GetProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1225,19 +1221,34 @@ def __call__( resp = self._interceptor.post_get_product(resp) return resp - class _ImportProducts(ProductServiceRestStub): + class _ImportProducts( + _BaseProductServiceRestTransport._BaseImportProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ImportProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ImportProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1266,45 +1277,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseImportProducts._get_http_options() + ) request, metadata = self._interceptor.pre_import_products(request, metadata) - pb_request = import_config.ImportProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseImportProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseImportProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseImportProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._ImportProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1318,19 +1316,33 @@ def __call__( resp = self._interceptor.post_import_products(resp) return resp - class _ListProducts(ProductServiceRestStub): + class _ListProducts( + _BaseProductServiceRestTransport._BaseListProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("ListProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.ListProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1361,38 +1373,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseListProducts._get_http_options() + ) request, metadata = self._interceptor.pre_list_products(request, metadata) - pb_request = product_service.ListProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListProducts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseListProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProductServiceRestTransport._ListProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1408,19 +1409,34 @@ def __call__( resp = self._interceptor.post_list_products(resp) return resp - class _PurgeProducts(ProductServiceRestStub): + class _PurgeProducts( + _BaseProductServiceRestTransport._BasePurgeProducts, ProductServiceRestStub + ): def __hash__(self): - return hash("PurgeProducts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.PurgeProducts") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1450,45 +1466,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BasePurgeProducts._get_http_options() + ) request, metadata = self._interceptor.pre_purge_products(request, metadata) - pb_request = purge_config.PurgeProductsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BasePurgeProducts._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BasePurgeProducts._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BasePurgeProducts._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._PurgeProducts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1502,19 +1505,35 @@ def __call__( resp = self._interceptor.post_purge_products(resp) return resp - class _RemoveFulfillmentPlaces(ProductServiceRestStub): + class _RemoveFulfillmentPlaces( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveFulfillmentPlaces") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveFulfillmentPlaces") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1545,47 +1564,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_http_options() + ) request, metadata = self._interceptor.pre_remove_fulfillment_places( request, metadata ) - pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveFulfillmentPlaces._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1599,19 +1607,35 @@ def __call__( resp = self._interceptor.post_remove_fulfillment_places(resp) return resp - class _RemoveLocalInventories(ProductServiceRestStub): + class _RemoveLocalInventories( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories, + ProductServiceRestStub, + ): def __hash__(self): - return hash("RemoveLocalInventories") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.RemoveLocalInventories") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1642,47 +1666,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_http_options() + ) request, metadata = self._interceptor.pre_remove_local_inventories( request, metadata ) - pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ProductServiceRestTransport._RemoveLocalInventories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1696,19 +1709,34 @@ def __call__( resp = self._interceptor.post_remove_local_inventories(resp) return resp - class _SetInventory(ProductServiceRestStub): + class _SetInventory( + _BaseProductServiceRestTransport._BaseSetInventory, ProductServiceRestStub + ): def __hash__(self): - return hash("SetInventory") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.SetInventory") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1739,45 +1767,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", - "body": "*", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseSetInventory._get_http_options() + ) request, metadata = self._interceptor.pre_set_inventory(request, metadata) - pb_request = product_service.SetInventoryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseSetInventory._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseSetInventory._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseSetInventory._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._SetInventory._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1791,19 +1806,34 @@ def __call__( resp = self._interceptor.post_set_inventory(resp) return resp - class _UpdateProduct(ProductServiceRestStub): + class _UpdateProduct( + _BaseProductServiceRestTransport._BaseUpdateProduct, ProductServiceRestStub + ): def __hash__(self): - return hash("UpdateProduct") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProductServiceRestTransport.UpdateProduct") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1834,45 +1864,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", - "body": "product", - }, - ] + http_options = ( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_http_options() + ) request, metadata = self._interceptor.pre_update_product(request, metadata) - pb_request = product_service.UpdateProductRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProductServiceRestTransport._BaseUpdateProduct._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProductServiceRestTransport._BaseUpdateProduct._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProductServiceRestTransport._BaseUpdateProduct._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProductServiceRestTransport._UpdateProduct._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2006,7 +2023,34 @@ def update_product( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProductServiceRestStub): + class _GetOperation( + _BaseProductServiceRestTransport._BaseGetOperation, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -2030,44 +2074,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2075,8 +2102,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -2084,7 +2112,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ProductServiceRestStub): + class _ListOperations( + _BaseProductServiceRestTransport._BaseListOperations, ProductServiceRestStub + ): + def __hash__(self): + return hash("ProductServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -2108,40 +2163,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseProductServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProductServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProductServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ProductServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2149,8 +2191,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest_base.py new file mode 100644 index 000000000000..1358fcd8a73d --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/product_service/transports/rest_base.py @@ -0,0 +1,880 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import export_config, import_config +from google.cloud.retail_v2beta.types import product +from google.cloud.retail_v2beta.types import product as gcr_product +from google.cloud.retail_v2beta.types import product_service, purge_config + +from .base import DEFAULT_CLIENT_INFO, ProductServiceTransport + + +class _BaseProductServiceRestTransport(ProductServiceTransport): + """Base REST backend transport for ProductService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseAddLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.AddLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseAddLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "productId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.CreateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseCreateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.DeleteProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseDeleteProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseExportProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.GetProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseGetProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseImportProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.ListProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseListProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeProducts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*/branches/*}/products:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeProductsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BasePurgeProducts._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveFulfillmentPlaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveFulfillmentPlacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveFulfillmentPlaces._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveLocalInventories: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.RemoveLocalInventoriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseRemoveLocalInventories._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetInventory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.SetInventoryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseSetInventory._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateProduct: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}", + "body": "product", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = product_service.UpdateProductRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProductServiceRestTransport._BaseUpdateProduct._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProductServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/async_client.py index 5aa25fa7f33a..b2b835e44270 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/async_client.py @@ -524,11 +524,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -581,11 +577,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/client.py index 57792ef42493..befae35925b5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/client.py @@ -947,11 +947,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1004,11 +1000,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/README.rst new file mode 100644 index 000000000000..e8af52d6e307 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProjectServiceTransport` is the ABC for all transports. +- public child `ProjectServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProjectServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProjectServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProjectServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/base.py index 9e8bff3aceaf..f9e1f4e928a1 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/base.py @@ -140,6 +140,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/grpc_asyncio.py index 9f25be82cb5a..fb8c3c53c905 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -300,21 +304,40 @@ def update_alert_config( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_alert_config: gapic_v1.method_async.wrap_method( + self.get_alert_config: self._wrap_method( self.get_alert_config, default_timeout=None, client_info=client_info, ), - self.update_alert_config: gapic_v1.method_async.wrap_method( + self.update_alert_config: self._wrap_method( self.update_alert_config, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest.py index 35cd7abc4100..e1c16e12b7eb 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2beta.types import project, project_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProjectServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2beta.types import project, project_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ProjectServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -188,8 +184,8 @@ class ProjectServiceRestStub: _interceptor: ProjectServiceRestInterceptor -class ProjectServiceRestTransport(ProjectServiceTransport): - """REST backend transport for ProjectService. +class ProjectServiceRestTransport(_BaseProjectServiceRestTransport): + """REST backend synchronous transport for ProjectService. Service for settings at Project level. @@ -198,7 +194,6 @@ class ProjectServiceRestTransport(ProjectServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -252,21 +247,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -277,19 +263,33 @@ def __init__( self._interceptor = interceptor or ProjectServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetAlertConfig(ProjectServiceRestStub): + class _GetAlertConfig( + _BaseProjectServiceRestTransport._BaseGetAlertConfig, ProjectServiceRestStub + ): def __hash__(self): - return hash("GetAlertConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.GetAlertConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -317,40 +317,29 @@ def __call__( Project level alert config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/alertConfig}", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_alert_config( request, metadata ) - pb_request = project_service.GetAlertConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ProjectServiceRestTransport._GetAlertConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -366,19 +355,34 @@ def __call__( resp = self._interceptor.post_get_alert_config(resp) return resp - class _UpdateAlertConfig(ProjectServiceRestStub): + class _UpdateAlertConfig( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig, ProjectServiceRestStub + ): def __hash__(self): - return hash("UpdateAlertConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ProjectServiceRestTransport.UpdateAlertConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -406,47 +410,34 @@ def __call__( Project level alert config. """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{alert_config.name=projects/*/alertConfig}", - "body": "alert_config", - }, - ] + http_options = ( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_alert_config( request, metadata ) - pb_request = project_service.UpdateAlertConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ProjectServiceRestTransport._UpdateAlertConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -482,7 +473,34 @@ def update_alert_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ProjectServiceRestStub): + class _GetOperation( + _BaseProjectServiceRestTransport._BaseGetOperation, ProjectServiceRestStub + ): + def __hash__(self): + return hash("ProjectServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -506,44 +524,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseProjectServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProjectServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ProjectServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -551,8 +552,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -560,7 +562,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ProjectServiceRestStub): + class _ListOperations( + _BaseProjectServiceRestTransport._BaseListOperations, ProjectServiceRestStub + ): + def __hash__(self): + return hash("ProjectServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -584,40 +613,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseProjectServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseProjectServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseProjectServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ProjectServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -625,8 +641,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest_base.py new file mode 100644 index 000000000000..8acfe9b04b74 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/project_service/transports/rest_base.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import project, project_service + +from .base import DEFAULT_CLIENT_INFO, ProjectServiceTransport + + +class _BaseProjectServiceRestTransport(ProjectServiceTransport): + """Base REST backend transport for ProjectService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetAlertConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/alertConfig}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.GetAlertConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseGetAlertConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAlertConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{alert_config.name=projects/*/alertConfig}", + "body": "alert_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = project_service.UpdateAlertConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseProjectServiceRestTransport._BaseUpdateAlertConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseProjectServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/async_client.py index 49526aa91cd3..1fdbb1b2c350 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/async_client.py @@ -407,11 +407,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -464,11 +460,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/client.py index 13aaa2a0b0e8..2f660aee1858 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/client.py @@ -909,11 +909,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -966,11 +962,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/README.rst new file mode 100644 index 000000000000..8ef0891e3c25 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SearchServiceTransport` is the ABC for all transports. +- public child `SearchServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SearchServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSearchServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SearchServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/base.py index 18569397d607..2679d1262ec8 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/base.py @@ -135,6 +135,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py index 2fedfc4a5fc5..8d8e2ba26e76 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -279,16 +283,35 @@ def search( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.search: gapic_v1.method_async.wrap_method( + self.search: self._wrap_method( self.search, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest.py index 04854dcd3cb5..1fe3ec7105e5 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.retail_v2beta.types import search_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSearchServiceRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.retail_v2beta.types import search_service - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import SearchServiceTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -155,8 +151,8 @@ class SearchServiceRestStub: _interceptor: SearchServiceRestInterceptor -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. +class SearchServiceRestTransport(_BaseSearchServiceRestTransport): + """REST backend synchronous transport for SearchService. Service for search. @@ -169,7 +165,6 @@ class SearchServiceRestTransport(SearchServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -223,21 +218,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -248,19 +234,32 @@ def __init__( self._interceptor = interceptor or SearchServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _Search(SearchServiceRestStub): + class _Search(_BaseSearchServiceRestTransport._BaseSearch, SearchServiceRestStub): def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("SearchServiceRestTransport.Search") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -291,50 +290,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", - "body": "*", - }, - { - "method": "post", - "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", - "body": "*", - }, - ] + http_options = ( + _BaseSearchServiceRestTransport._BaseSearch._get_http_options() + ) request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseSearchServiceRestTransport._BaseSearch._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseSearchServiceRestTransport._BaseSearch._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseSearchServiceRestTransport._BaseSearch._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = SearchServiceRestTransport._Search._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -362,7 +347,34 @@ def search( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(SearchServiceRestStub): + class _GetOperation( + _BaseSearchServiceRestTransport._BaseGetOperation, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -386,44 +398,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -431,8 +426,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -440,7 +436,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(SearchServiceRestStub): + class _ListOperations( + _BaseSearchServiceRestTransport._BaseListOperations, SearchServiceRestStub + ): + def __hash__(self): + return hash("SearchServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -464,40 +487,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseSearchServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseSearchServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseSearchServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = SearchServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -505,8 +515,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest_base.py new file mode 100644 index 000000000000..ad30beaa7f33 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/search_service/transports/rest_base.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import search_service + +from .base import DEFAULT_CLIENT_INFO, SearchServiceTransport + + +class _BaseSearchServiceRestTransport(SearchServiceTransport): + """Base REST backend transport for SearchService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseSearch: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/placements/*}:search", + "body": "*", + }, + { + "method": "post", + "uri": "/v2beta/{placement=projects/*/locations/*/catalogs/*/servingConfigs/*}:search", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSearchServiceRestTransport._BaseSearch._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSearchServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/async_client.py index 0796bf5e6df0..df6da8aa0277 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/async_client.py @@ -1144,11 +1144,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1201,11 +1197,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/client.py index b9a0d2989f0e..b07c3b950b00 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/client.py @@ -1580,11 +1580,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1637,11 +1633,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/README.rst new file mode 100644 index 000000000000..0581bb81c691 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ServingConfigServiceTransport` is the ABC for all transports. +- public child `ServingConfigServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ServingConfigServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseServingConfigServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ServingConfigServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py index 7f4f76726a2a..f774aea8f878 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/base.py @@ -168,6 +168,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py index 93e4d00b8c7e..8a2ab4b03bc8 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -231,6 +232,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -467,46 +471,65 @@ def remove_control( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_serving_config: gapic_v1.method_async.wrap_method( + self.create_serving_config: self._wrap_method( self.create_serving_config, default_timeout=None, client_info=client_info, ), - self.delete_serving_config: gapic_v1.method_async.wrap_method( + self.delete_serving_config: self._wrap_method( self.delete_serving_config, default_timeout=None, client_info=client_info, ), - self.update_serving_config: gapic_v1.method_async.wrap_method( + self.update_serving_config: self._wrap_method( self.update_serving_config, default_timeout=None, client_info=client_info, ), - self.get_serving_config: gapic_v1.method_async.wrap_method( + self.get_serving_config: self._wrap_method( self.get_serving_config, default_timeout=None, client_info=client_info, ), - self.list_serving_configs: gapic_v1.method_async.wrap_method( + self.list_serving_configs: self._wrap_method( self.list_serving_configs, default_timeout=None, client_info=client_info, ), - self.add_control: gapic_v1.method_async.wrap_method( + self.add_control: self._wrap_method( self.add_control, default_timeout=None, client_info=client_info, ), - self.remove_control: gapic_v1.method_async.wrap_method( + self.remove_control: self._wrap_method( self.remove_control, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest.py index 43358191aa70..63f65e238033 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest.py @@ -16,36 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config from google.cloud.retail_v2beta.types import serving_config from google.cloud.retail_v2beta.types import serving_config_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ServingConfigServiceTransport +from .rest_base import _BaseServingConfigServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -341,8 +337,8 @@ class ServingConfigServiceRestStub: _interceptor: ServingConfigServiceRestInterceptor -class ServingConfigServiceRestTransport(ServingConfigServiceTransport): - """REST backend transport for ServingConfigService. +class ServingConfigServiceRestTransport(_BaseServingConfigServiceRestTransport): + """REST backend synchronous transport for ServingConfigService. Service for modifying ServingConfig. @@ -351,7 +347,6 @@ class ServingConfigServiceRestTransport(ServingConfigServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -405,21 +400,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -430,19 +416,35 @@ def __init__( self._interceptor = interceptor or ServingConfigServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AddControl(ServingConfigServiceRestStub): + class _AddControl( + _BaseServingConfigServiceRestTransport._BaseAddControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("AddControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.AddControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -472,45 +474,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_http_options() + ) request, metadata = self._interceptor.pre_add_control(request, metadata) - pb_request = serving_config_service.AddControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseAddControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseAddControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseAddControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._AddControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -526,21 +515,35 @@ def __call__( resp = self._interceptor.post_add_control(resp) return resp - class _CreateServingConfig(ServingConfigServiceRestStub): + class _CreateServingConfig( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("CreateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "servingConfigId": "", - } - - @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 - } + return hash("ServingConfigServiceRestTransport.CreateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -571,47 +574,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_create_serving_config( request, metadata ) - pb_request = serving_config_service.CreateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._CreateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -627,19 +619,34 @@ def __call__( resp = self._interceptor.post_create_serving_config(resp) return resp - class _DeleteServingConfig(ServingConfigServiceRestStub): + class _DeleteServingConfig( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("DeleteServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.DeleteServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -662,40 +669,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_delete_serving_config( request, metadata ) - pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._DeleteServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -703,19 +701,34 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _GetServingConfig(ServingConfigServiceRestStub): + class _GetServingConfig( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("GetServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.GetServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -745,40 +758,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_get_serving_config( request, metadata ) - pb_request = serving_config_service.GetServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._GetServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -794,19 +798,34 @@ def __call__( resp = self._interceptor.post_get_serving_config(resp) return resp - class _ListServingConfigs(ServingConfigServiceRestStub): + class _ListServingConfigs( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("ListServingConfigs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.ListServingConfigs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -835,40 +854,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_http_options() + ) request, metadata = self._interceptor.pre_list_serving_configs( request, metadata ) - pb_request = serving_config_service.ListServingConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ( + ServingConfigServiceRestTransport._ListServingConfigs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -884,19 +894,35 @@ def __call__( resp = self._interceptor.post_list_serving_configs(resp) return resp - class _RemoveControl(ServingConfigServiceRestStub): + class _RemoveControl( + _BaseServingConfigServiceRestTransport._BaseRemoveControl, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("RemoveControl") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.RemoveControl") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -926,45 +952,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", - "body": "*", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_http_options() + ) request, metadata = self._interceptor.pre_remove_control(request, metadata) - pb_request = serving_config_service.RemoveControlRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServingConfigServiceRestTransport._RemoveControl._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -980,19 +993,35 @@ def __call__( resp = self._interceptor.post_remove_control(resp) return resp - class _UpdateServingConfig(ServingConfigServiceRestStub): + class _UpdateServingConfig( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig, + ServingConfigServiceRestStub, + ): def __hash__(self): - return hash("UpdateServingConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServingConfigServiceRestTransport.UpdateServingConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1023,47 +1052,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2beta/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", - "body": "serving_config", - }, - ] + http_options = ( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_http_options() + ) request, metadata = self._interceptor.pre_update_serving_config( request, metadata ) - pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ( + ServingConfigServiceRestTransport._UpdateServingConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1154,7 +1172,35 @@ def update_serving_config( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ServingConfigServiceRestStub): + class _GetOperation( + _BaseServingConfigServiceRestTransport._BaseGetOperation, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1178,44 +1224,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1223,8 +1252,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1232,7 +1262,35 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ServingConfigServiceRestStub): + class _ListOperations( + _BaseServingConfigServiceRestTransport._BaseListOperations, + ServingConfigServiceRestStub, + ): + def __hash__(self): + return hash("ServingConfigServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1256,40 +1314,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseServingConfigServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseServingConfigServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseServingConfigServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = ServingConfigServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1297,8 +1342,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest_base.py new file mode 100644 index 000000000000..98339268e61d --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/serving_config_service/transports/rest_base.py @@ -0,0 +1,537 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import serving_config as gcr_serving_config +from google.cloud.retail_v2beta.types import serving_config +from google.cloud.retail_v2beta.types import serving_config_service + +from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport + + +class _BaseServingConfigServiceRestTransport(ServingConfigServiceTransport): + """Base REST backend transport for ServingConfigService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseAddControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.AddControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseAddControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "servingConfigId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.CreateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.DeleteServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.GetServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServingConfigs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.ListServingConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveControl: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.RemoveControlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseRemoveControl._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateServingConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}", + "body": "serving_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = serving_config_service.UpdateServingConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseServingConfigServiceRestTransport",) diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/async_client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/async_client.py index 4c991a2c3be8..b85b0fb3a6d2 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/async_client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/async_client.py @@ -968,11 +968,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1025,11 +1021,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/client.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/client.py index 08bc8d8b97ee..6725197679d6 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/client.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/client.py @@ -1417,11 +1417,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1474,11 +1470,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/README.rst b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/README.rst new file mode 100644 index 000000000000..45f0ef746528 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserEventServiceTransport` is the ABC for all transports. +- public child `UserEventServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserEventServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserEventServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserEventServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/base.py index 3ffc64b62fab..6c88c6fe47cd 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/base.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/base.py @@ -187,6 +187,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py index f32491d3baae..ffabc7e14c7b 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -237,6 +238,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -466,17 +470,17 @@ def rejoin_user_events( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.write_user_event: gapic_v1.method_async.wrap_method( + self.write_user_event: self._wrap_method( self.write_user_event, default_timeout=None, client_info=client_info, ), - self.collect_user_event: gapic_v1.method_async.wrap_method( + self.collect_user_event: self._wrap_method( self.collect_user_event, default_timeout=None, client_info=client_info, ), - self.purge_user_events: gapic_v1.method_async.wrap_method( + self.purge_user_events: self._wrap_method( self.purge_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -491,7 +495,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=30.0, client_info=client_info, ), - self.import_user_events: gapic_v1.method_async.wrap_method( + self.import_user_events: self._wrap_method( self.import_user_events, default_retry=retries.AsyncRetry( initial=0.1, @@ -506,21 +510,40 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), - self.export_user_events: gapic_v1.method_async.wrap_method( + self.export_user_events: self._wrap_method( self.export_user_events, default_timeout=None, client_info=client_info, ), - self.rejoin_user_events: gapic_v1.method_async.wrap_method( + self.rejoin_user_events: self._wrap_method( self.rejoin_user_events, default_timeout=None, client_info=client_info, ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def get_operation( self, diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest.py index e912baee8a47..83986eec0d80 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest.py @@ -16,36 +16,20 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - from google.cloud.retail_v2beta.types import ( export_config, import_config, @@ -55,7 +39,13 @@ ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import UserEventServiceTransport +from .rest_base import _BaseUserEventServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -325,8 +315,8 @@ class UserEventServiceRestStub: _interceptor: UserEventServiceRestInterceptor -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. +class UserEventServiceRestTransport(_BaseUserEventServiceRestTransport): + """REST backend synchronous transport for UserEventService. Service for ingesting end user actions on the customer website. @@ -336,7 +326,6 @@ class UserEventServiceRestTransport(UserEventServiceTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -390,21 +379,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -476,21 +456,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CollectUserEvent(UserEventServiceRestStub): + class _CollectUserEvent( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent": "", - } - - @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 - } + return hash("UserEventServiceRestTransport.CollectUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -566,40 +559,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_collect_user_event( request, metadata ) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = UserEventServiceRestTransport._CollectUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -615,19 +597,35 @@ def __call__( resp = self._interceptor.post_collect_user_event(resp) return resp - class _ExportUserEvents(UserEventServiceRestStub): + class _ExportUserEvents( + _BaseUserEventServiceRestTransport._BaseExportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ExportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ExportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -656,47 +654,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:export", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_export_user_events( request, metadata ) - pb_request = export_config.ExportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ExportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -710,19 +695,35 @@ def __call__( resp = self._interceptor.post_export_user_events(resp) return resp - class _ImportUserEvents(UserEventServiceRestStub): + class _ImportUserEvents( + _BaseUserEventServiceRestTransport._BaseImportUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.ImportUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -752,47 +753,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_import_user_events( request, metadata ) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._ImportUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -806,19 +794,35 @@ def __call__( resp = self._interceptor.post_import_user_events(resp) return resp - class _PurgeUserEvents(UserEventServiceRestStub): + class _PurgeUserEvents( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("PurgeUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.PurgeUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -848,47 +852,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_purge_user_events( request, metadata ) - pb_request = purge_config.PurgeUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._PurgeUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -902,19 +893,35 @@ def __call__( resp = self._interceptor.post_purge_user_events(resp) return resp - class _RejoinUserEvents(UserEventServiceRestStub): + class _RejoinUserEvents( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents, + UserEventServiceRestStub, + ): def __hash__(self): - return hash("RejoinUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.RejoinUserEvents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -944,47 +951,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", - "body": "*", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_http_options() + ) request, metadata = self._interceptor.pre_rejoin_user_events( request, metadata ) - pb_request = user_event_service.RejoinUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._RejoinUserEvents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -998,19 +992,34 @@ def __call__( resp = self._interceptor.post_rejoin_user_events(resp) return resp - class _WriteUserEvent(UserEventServiceRestStub): + class _WriteUserEvent( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent, UserEventServiceRestStub + ): def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("UserEventServiceRestTransport.WriteUserEvent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1041,47 +1050,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", - "body": "user_event", - }, - ] + http_options = ( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_http_options() + ) request, metadata = self._interceptor.pre_write_user_event( request, metadata ) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = UserEventServiceRestTransport._WriteUserEvent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1151,7 +1147,34 @@ def write_user_event( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(UserEventServiceRestStub): + class _GetOperation( + _BaseUserEventServiceRestTransport._BaseGetOperation, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1175,44 +1198,27 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/operations/*}", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1220,8 +1226,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1229,7 +1236,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(UserEventServiceRestStub): + class _ListOperations( + _BaseUserEventServiceRestTransport._BaseListOperations, UserEventServiceRestStub + ): + def __hash__(self): + return hash("UserEventServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1253,40 +1287,27 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*/locations/*}/operations", - }, - { - "method": "get", - "uri": "/v2beta/{name=projects/*}/operations", - }, - ] - + http_options = ( + _BaseUserEventServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseUserEventServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseUserEventServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) # 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), + response = UserEventServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1294,8 +1315,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp diff --git a/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest_base.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest_base.py new file mode 100644 index 000000000000..a811a7ac8166 --- /dev/null +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/services/user_event_service/transports/rest_base.py @@ -0,0 +1,504 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.retail_v2beta.types import ( + export_config, + import_config, + purge_config, + user_event, + user_event_service, +) + +from .base import DEFAULT_CLIENT_INFO, UserEventServiceTransport + + +class _BaseUserEventServiceRestTransport(UserEventServiceTransport): + """Base REST backend transport for UserEventService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "retail.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'retail.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCollectUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:collect", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseCollectUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = export_config.ExportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseExportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:import", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseImportUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePurgeUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:purge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = purge_config.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BasePurgeUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRejoinUserEvents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:rejoin", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.RejoinUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseRejoinUserEvents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseWriteUserEvent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=projects/*/locations/*/catalogs/*}/userEvents:write", + "body": "user_event", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseUserEventServiceRestTransport._BaseWriteUserEvent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*/catalogs/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v2beta/{name=projects/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseUserEventServiceRestTransport",) diff --git a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json index e14d949e197f..bd7fbc1b355a 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.22.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json index 84facd97aa38..2bad2703cfbd 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.22.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json index c06448158920..7d1d63860fc2 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.22.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-retail/setup.py b/packages/google-cloud-retail/setup.py index 82cfc53cec98..e9333c6f110e 100644 --- a/packages/google-cloud-retail/setup.py +++ b/packages/google-cloud-retail/setup.py @@ -46,6 +46,7 @@ "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -88,6 +89,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_analytics_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_analytics_service.py index fff3af8ebdc0..3c2f65225393 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_analytics_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_analytics_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,14 +62,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2.services.analytics_service import ( AnalyticsServiceAsyncClient, @@ -62,10 +71,24 @@ from google.cloud.retail_v2.types import export_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1192,27 +1215,6 @@ def test_export_analytics_metrics(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_analytics_metrics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - def test_export_analytics_metrics_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,29 +1292,6 @@ def test_export_analytics_metrics_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_analytics_metrics_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - @pytest.mark.asyncio async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1321,7 +1300,7 @@ async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1345,7 @@ async def test_export_analytics_metrics_async( request_type=export_config.ExportAnalyticsMetricsRequest, ): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_export_analytics_metrics_field_headers(): @pytest.mark.asyncio async def test_export_analytics_metrics_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1464,41 +1443,6 @@ async def test_export_analytics_metrics_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportAnalyticsMetricsRequest, - dict, - ], -) -def test_export_analytics_metrics_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_analytics_metrics(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_analytics_metrics_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1633,95 +1577,6 @@ def test_export_analytics_metrics_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_analytics_metrics_rest_interceptors(null_interceptor): - transport = transports.AnalyticsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AnalyticsServiceRestInterceptor(), - ) - client = AnalyticsServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" - ) as post, mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportAnalyticsMetricsRequest.pb( - export_config.ExportAnalyticsMetricsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportAnalyticsMetricsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_analytics_metrics( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_analytics_metrics_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportAnalyticsMetricsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.export_analytics_metrics(request) - - -def test_export_analytics_metrics_rest_error(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnalyticsServiceGrpcTransport( @@ -1814,87 +1669,439 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = AnalyticsServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = AnalyticsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.AnalyticsServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_analytics_metrics(request=None) -def test_analytics_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + assert args[0] == request_msg -def test_analytics_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2.services.analytics_service.transports.AnalyticsServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "export_analytics_metrics", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = AnalyticsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - with pytest.raises(NotImplementedError): - transport.close() - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client +def test_initialize_client_w_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_analytics_metrics_empty_call_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_analytics_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.retail_v2.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AnalyticsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_export_analytics_metrics_rest_bad_request( + request_type=export_config.ExportAnalyticsMetricsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_analytics_metrics(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportAnalyticsMetricsRequest, + dict, + ], +) +def test_export_analytics_metrics_rest_call_success(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_analytics_metrics(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_analytics_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsServiceRestInterceptor(), + ) + client = AnalyticsServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" + ) as post, mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportAnalyticsMetricsRequest.pb( + export_config.ExportAnalyticsMetricsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportAnalyticsMetricsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_analytics_metrics( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_analytics_service_rest_lro_client(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnalyticsServiceGrpcTransport, + ) + + +def test_analytics_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_analytics_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2.services.analytics_service.transports.AnalyticsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "export_analytics_metrics", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_analytics_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.retail_v2.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnalyticsServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", @@ -2064,23 +2271,6 @@ def test_analytics_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_analytics_service_rest_lro_client(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -2435,136 +2625,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = AnalyticsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2592,7 +2652,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2647,7 +2707,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2694,7 +2754,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2737,7 +2797,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2792,7 +2852,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2839,7 +2899,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2855,22 +2915,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_catalog_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_catalog_service.py index 78d7cc610df2..116662ab4d9d 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_catalog_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_catalog_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,16 +54,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import date_pb2 # type: ignore -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.retail_v2.services.catalog_service import ( CatalogServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2.types import catalog_service, common, import_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1160,25 +1183,6 @@ def test_list_catalogs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - def test_list_catalogs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1244,29 +1248,6 @@ def test_list_catalogs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_catalogs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - @pytest.mark.asyncio async def test_list_catalogs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1275,7 +1256,7 @@ async def test_list_catalogs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1314,7 +1295,7 @@ async def test_list_catalogs_async( transport: str = "grpc_asyncio", request_type=catalog_service.ListCatalogsRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1380,7 +1361,7 @@ def test_list_catalogs_field_headers(): @pytest.mark.asyncio async def test_list_catalogs_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1450,7 +1431,7 @@ def test_list_catalogs_flattened_error(): @pytest.mark.asyncio async def test_list_catalogs_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1479,7 +1460,7 @@ async def test_list_catalogs_flattened_async(): @pytest.mark.asyncio async def test_list_catalogs_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1589,7 +1570,7 @@ def test_list_catalogs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_catalogs_async_pager(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1639,7 +1620,7 @@ async def test_list_catalogs_async_pager(): @pytest.mark.asyncio async def test_list_catalogs_async_pages(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1723,25 +1704,6 @@ def test_update_catalog(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - def test_update_catalog_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1801,30 +1763,6 @@ def test_update_catalog_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_catalog_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - @pytest.mark.asyncio async def test_update_catalog_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1833,7 +1771,7 @@ async def test_update_catalog_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1872,7 +1810,7 @@ async def test_update_catalog_async( transport: str = "grpc_asyncio", request_type=catalog_service.UpdateCatalogRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1940,7 +1878,7 @@ def test_update_catalog_field_headers(): @pytest.mark.asyncio async def test_update_catalog_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2013,7 +1951,7 @@ def test_update_catalog_flattened_error(): @pytest.mark.asyncio async def test_update_catalog_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1982,7 @@ async def test_update_catalog_flattened_async(): @pytest.mark.asyncio async def test_update_catalog_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2092,27 +2030,6 @@ def test_set_default_branch(request_type, transport: str = "grpc"): assert response is None -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - def test_set_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2186,27 +2103,6 @@ def test_set_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_set_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2215,7 +2111,7 @@ async def test_set_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2255,7 +2151,7 @@ async def test_set_default_branch_async( request_type=catalog_service.SetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2320,7 +2216,7 @@ def test_set_default_branch_field_headers(): @pytest.mark.asyncio async def test_set_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2392,7 +2288,7 @@ def test_set_default_branch_flattened_error(): @pytest.mark.asyncio async def test_set_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2421,7 +2317,7 @@ async def test_set_default_branch_flattened_async(): @pytest.mark.asyncio async def test_set_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2473,27 +2369,6 @@ def test_get_default_branch(request_type, transport: str = "grpc"): assert response.note == "note_value" -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - def test_get_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2563,32 +2438,6 @@ def test_get_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - ) - response = await client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_get_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2597,7 +2446,7 @@ async def test_get_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2637,7 +2486,7 @@ async def test_get_default_branch_async( request_type=catalog_service.GetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2709,7 +2558,7 @@ def test_get_default_branch_field_headers(): @pytest.mark.asyncio async def test_get_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2783,7 +2632,7 @@ def test_get_default_branch_flattened_error(): @pytest.mark.asyncio async def test_get_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2814,7 +2663,7 @@ async def test_get_default_branch_flattened_async(): @pytest.mark.asyncio async def test_get_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2887,27 +2736,6 @@ def test_get_completion_config(request_type, transport: str = "grpc"): ) -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - def test_get_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2978,38 +2806,6 @@ def test_get_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - @pytest.mark.asyncio async def test_get_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3018,7 +2814,7 @@ async def test_get_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3058,7 +2854,7 @@ async def test_get_completion_config_async( request_type=catalog_service.GetCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3151,7 +2947,7 @@ def test_get_completion_config_field_headers(): @pytest.mark.asyncio async def test_get_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3225,7 +3021,7 @@ def test_get_completion_config_flattened_error(): @pytest.mark.asyncio async def test_get_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3256,7 +3052,7 @@ async def test_get_completion_config_flattened_async(): @pytest.mark.asyncio async def test_get_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3329,27 +3125,6 @@ def test_update_completion_config(request_type, transport: str = "grpc"): ) -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - def test_update_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3416,38 +3191,6 @@ def test_update_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - @pytest.mark.asyncio async def test_update_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3456,7 +3199,7 @@ async def test_update_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3496,7 +3239,7 @@ async def test_update_completion_config_async( request_type=catalog_service.UpdateCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3589,7 +3332,7 @@ def test_update_completion_config_field_headers(): @pytest.mark.asyncio async def test_update_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3668,7 +3411,7 @@ def test_update_completion_config_flattened_error(): @pytest.mark.asyncio async def test_update_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3703,7 +3446,7 @@ async def test_update_completion_config_flattened_async(): @pytest.mark.asyncio async def test_update_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3759,27 +3502,6 @@ def test_get_attributes_config(request_type, transport: str = "grpc"): ) -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - def test_get_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3850,32 +3572,6 @@ def test_get_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - @pytest.mark.asyncio async def test_get_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3884,7 +3580,7 @@ async def test_get_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3924,7 +3620,7 @@ async def test_get_attributes_config_async( request_type=catalog_service.GetAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3999,7 +3695,7 @@ def test_get_attributes_config_field_headers(): @pytest.mark.asyncio async def test_get_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4073,7 +3769,7 @@ def test_get_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4104,7 +3800,7 @@ async def test_get_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4159,27 +3855,6 @@ def test_update_attributes_config(request_type, transport: str = "grpc"): ) -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - def test_update_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4246,32 +3921,6 @@ def test_update_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - @pytest.mark.asyncio async def test_update_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4280,7 +3929,7 @@ async def test_update_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4320,7 +3969,7 @@ async def test_update_attributes_config_async( request_type=catalog_service.UpdateAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4395,7 +4044,7 @@ def test_update_attributes_config_field_headers(): @pytest.mark.asyncio async def test_update_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4474,7 +4123,7 @@ def test_update_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4509,7 +4158,7 @@ async def test_update_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4565,27 +4214,6 @@ def test_add_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - def test_add_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4656,32 +4284,6 @@ def test_add_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4690,7 +4292,7 @@ async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4730,7 +4332,7 @@ async def test_add_catalog_attribute_async( request_type=catalog_service.AddCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4805,7 +4407,7 @@ def test_add_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_add_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4879,27 +4481,6 @@ def test_remove_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - def test_remove_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4972,32 +4553,6 @@ def test_remove_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5006,7 +4561,7 @@ async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5046,7 +4601,7 @@ async def test_remove_catalog_attribute_async( request_type=catalog_service.RemoveCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5121,7 +4676,7 @@ def test_remove_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_remove_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5195,27 +4750,6 @@ def test_replace_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - def test_replace_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5286,32 +4820,6 @@ def test_replace_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_replace_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5320,7 +4828,7 @@ async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5360,7 +4868,7 @@ async def test_replace_catalog_attribute_async( request_type=catalog_service.ReplaceCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5435,7 +4943,7 @@ def test_replace_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_replace_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5466,58 +4974,18 @@ async def test_replace_catalog_attribute_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.ListCatalogsRequest, - dict, - ], -) -def test_list_catalogs_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_catalogs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + 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 = catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.ListCatalogsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_catalogs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_catalogs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.list_catalogs in client._transport._wrapped_methods @@ -5640,87 +5108,6 @@ def test_list_catalogs_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_catalogs_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_list_catalogs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.ListCatalogsRequest.pb( - catalog_service.ListCatalogsRequest() - ) - 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 = catalog_service.ListCatalogsResponse.to_json( - catalog_service.ListCatalogsResponse() - ) - - request = catalog_service.ListCatalogsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.ListCatalogsResponse() - - client.list_catalogs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_catalogs_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ListCatalogsRequest -): - client = CatalogServiceClient( - 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.list_catalogs(request) - - def test_list_catalogs_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5840,125 +5227,6 @@ def test_list_catalogs_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCatalogRequest, - dict, - ], -) -def test_update_catalog_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} - } - request_init["catalog"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3", - "display_name": "display_name_value", - "product_level_config": { - "ingestion_product_type": "ingestion_product_type_value", - "merchant_center_product_id_field": "merchant_center_product_id_field_value", - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["catalog"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["catalog"][field])): - del request_init["catalog"][field][i][subfield] - else: - del request_init["catalog"][field][subfield] - 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 = gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_catalog.Catalog.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_catalog(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - - def test_update_catalog_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6076,91 +5344,10 @@ def test_update_catalog_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_catalog_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_update_catalog_rest_flattened(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_catalog" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCatalogRequest.pb( - catalog_service.UpdateCatalogRequest() - ) - 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 = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) - - request = catalog_service.UpdateCatalogRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_catalog.Catalog() - - client.update_catalog( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_catalog_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCatalogRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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.update_catalog(request) - - -def test_update_catalog_rest_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -6218,47 +5405,6 @@ def test_update_catalog_rest_flattened_error(transport: str = "rest"): ) -def test_update_catalog_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.SetDefaultBranchRequest, - dict, - ], -) -def test_set_default_branch_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_default_branch(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_set_default_branch_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6299,79 +5445,6 @@ def test_set_default_branch_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" - ) as pre: - pre.assert_not_called() - pb_message = catalog_service.SetDefaultBranchRequest.pb( - catalog_service.SetDefaultBranchRequest() - ) - 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() - - request = catalog_service.SetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.set_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_set_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.SetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.set_default_branch(request) - - def test_set_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6429,54 +5502,6 @@ def test_set_default_branch_rest_flattened_error(transport: str = "rest"): ) -def test_set_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetDefaultBranchRequest, - dict, - ], -) -def test_get_default_branch_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_default_branch(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == "branch_value" - assert response.note == "note_value" - - def test_get_default_branch_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6517,106 +5542,25 @@ def test_get_default_branch_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_get_default_branch_rest_flattened(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), + transport="rest", ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_default_branch" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetDefaultBranchRequest.pb( - catalog_service.GetDefaultBranchRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = catalog_service.GetDefaultBranchResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = catalog_service.GetDefaultBranchResponse.to_json( - catalog_service.GetDefaultBranchResponse() - ) - - request = catalog_service.GetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.GetDefaultBranchResponse() - - client.get_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.get_default_branch(request) - - -def test_get_default_branch_rest_flattened(): - client = CatalogServiceClient( - 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 = catalog_service.GetDefaultBranchResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - catalog="catalog_value", + # get truthy value for each flattened field + mock_args = dict( + catalog="catalog_value", ) mock_args.update(sample_request) @@ -6657,77 +5601,6 @@ def test_get_default_branch_rest_flattened_error(transport: str = "rest"): ) -def test_get_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetCompletionConfigRequest, - dict, - ], -) -def test_get_completion_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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 = catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_completion_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" - ) - - def test_get_completion_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6852,89 +5725,6 @@ def test_get_completion_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetCompletionConfigRequest.pb( - catalog_service.GetCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.GetCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.get_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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_completion_config(request) - - def test_get_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6994,188 +5784,24 @@ def test_get_completion_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_completion_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCompletionConfigRequest, - dict, - ], -) -def test_update_completion_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - request_init["completion_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", - "matching_order": "matching_order_value", - "max_suggestions": 1632, - "min_prefix_length": 1810, - "auto_learning": True, - "suggestions_input_config": { - "big_query_source": { - "partition_date": {"year": 433, "month": 550, "day": 318}, - "project_id": "project_id_value", - "dataset_id": "dataset_id_value", - "table_id": "table_id_value", - "gcs_staging_dir": "gcs_staging_dir_value", - "data_schema": "data_schema_value", - } - }, - "last_suggestions_import_operation": "last_suggestions_import_operation_value", - "denylist_input_config": {}, - "last_denylist_import_operation": "last_denylist_import_operation_value", - "allowlist_input_config": {}, - "last_allowlist_import_operation": "last_allowlist_import_operation_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ - "completion_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["completion_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["completion_config"][field])): - del request_init["completion_config"][field][i][subfield] - else: - del request_init["completion_config"][field][subfield] - 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 = catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_completion_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" - ) - - -def test_update_completion_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_completion_config - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_completion_config + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -7280,91 +5906,6 @@ def test_update_completion_config_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("completionConfig",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCompletionConfigRequest.pb( - catalog_service.UpdateCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.UpdateCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.update_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - 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_completion_config(request) - - def test_update_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7428,71 +5969,18 @@ def test_update_completion_config_rest_flattened_error(transport: str = "rest"): ) -def test_update_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_get_attributes_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetAttributesConfigRequest, - dict, - ], -) -def test_get_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - -def test_get_attributes_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( @@ -7605,89 +6093,6 @@ def test_get_attributes_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetAttributesConfigRequest.pb( - catalog_service.GetAttributesConfigRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.GetAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.get_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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_attributes_config(request) - - def test_get_attributes_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7747,135 +6152,6 @@ def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateAttributesConfigRequest, - dict, - ], -) -def test_update_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - request_init["attributes_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", - "catalog_attributes": {}, - "attribute_config_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ - "attributes_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["attributes_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["attributes_config"][field])): - del request_init["attributes_config"][field][i][subfield] - else: - del request_init["attributes_config"][field][subfield] - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - def test_update_attributes_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7998,91 +6274,6 @@ def test_update_attributes_config_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("attributesConfig",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateAttributesConfigRequest.pb( - catalog_service.UpdateAttributesConfigRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.UpdateAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.update_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - 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_attributes_config(request) - - def test_update_attributes_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8146,59 +6337,6 @@ def test_update_attributes_config_rest_flattened_error(transport: str = "rest"): ) -def test_update_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.AddCatalogAttributeRequest, - dict, - ], -) -def test_add_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_catalog_attribute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8332,203 +6470,67 @@ def test_add_catalog_attribute_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_add_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.AddCatalogAttributeRequest.pb( - catalog_service.AddCatalogAttributeRequest() +def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - request = catalog_service.AddCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() + # Ensure method has been cached + assert ( + client._transport.remove_catalog_attribute + in client._transport._wrapped_methods + ) - client.add_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.remove_catalog_attribute + ] = mock_rpc - pre.assert_called_once() - post.assert_called_once() + request = {} + client.remove_catalog_attribute(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_add_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.AddCatalogAttributeRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.remove_catalog_attribute(request) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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.add_catalog_attribute(request) +def test_remove_catalog_attribute_rest_required_fields( + request_type=catalog_service.RemoveCatalogAttributeRequest, +): + transport_class = transports.CatalogServiceRestTransport -def test_add_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + request_init = {} + request_init["attributes_config"] = "" + request_init["key"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.RemoveCatalogAttributeRequest, - dict, - ], -) -def test_remove_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_catalog_attribute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - -def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.remove_catalog_attribute - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_catalog_attribute - ] = mock_rpc - - request = {} - client.remove_catalog_attribute(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.remove_catalog_attribute(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_remove_catalog_attribute_rest_required_fields( - request_type=catalog_service.RemoveCatalogAttributeRequest, -): - transport_class = transports.CatalogServiceRestTransport - - request_init = {} - request_init["attributes_config"] = "" - request_init["key"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -8605,142 +6607,6 @@ def test_remove_catalog_attribute_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( - catalog_service.RemoveCatalogAttributeRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.RemoveCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.remove_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_remove_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.RemoveCatalogAttributeRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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.remove_catalog_attribute(request) - - -def test_remove_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.ReplaceCatalogAttributeRequest, - dict, - ], -) -def test_replace_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.replace_catalog_attribute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - def test_replace_catalog_attribute_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8874,42 +6740,2348 @@ def test_replace_catalog_attribute_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_replace_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_replace_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_replace_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.ReplaceCatalogAttributeRequest.pb( - catalog_service.ReplaceCatalogAttributeRequest() + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CatalogServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + call.return_value = None + client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CatalogServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_catalogs_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_catalog_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + ) + await client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + ) + await client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_replace_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CatalogServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_catalogs_rest_bad_request( + request_type=catalog_service.ListCatalogsRequest, +): + client = CatalogServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_catalogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ListCatalogsRequest, + dict, + ], +) +def test_list_catalogs_rest_call_success(request_type): + client = CatalogServiceClient( + 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 = catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.ListCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_catalogs_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_list_catalogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ListCatalogsRequest.pb( + catalog_service.ListCatalogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.ListCatalogsResponse.to_json( + catalog_service.ListCatalogsResponse() + ) + req.return_value.content = return_value + + request = catalog_service.ListCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.ListCatalogsResponse() + + client.list_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_catalog_rest_bad_request( + request_type=catalog_service.UpdateCatalogRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCatalogRequest, + dict, + ], +) +def test_update_catalog_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + } + request_init["catalog"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3", + "display_name": "display_name_value", + "product_level_config": { + "ingestion_product_type": "ingestion_product_type_value", + "merchant_center_product_id_field": "merchant_center_product_id_field_value", + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["catalog"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["catalog"][field])): + del request_init["catalog"][field][i][subfield] + else: + del request_init["catalog"][field][subfield] + 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 = gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_catalog.Catalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_catalog_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_catalog" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCatalogRequest.pb( + catalog_service.UpdateCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) + req.return_value.content = return_value + + request = catalog_service.UpdateCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_catalog.Catalog() + + client.update_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_default_branch_rest_bad_request( + request_type=catalog_service.SetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.SetDefaultBranchRequest, + dict, + ], +) +def test_set_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_default_branch(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" + ) as pre: + pre.assert_not_called() + pb_message = catalog_service.SetDefaultBranchRequest.pb( + catalog_service.SetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = catalog_service.SetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.set_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_default_branch_rest_bad_request( + request_type=catalog_service.GetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetDefaultBranchRequest, + dict, + ], +) +def test_get_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_default_branch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == "branch_value" + assert response.note == "note_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_default_branch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetDefaultBranchRequest.pb( + catalog_service.GetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.GetDefaultBranchResponse.to_json( + catalog_service.GetDefaultBranchResponse() + ) + req.return_value.content = return_value + + request = catalog_service.GetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.GetDefaultBranchResponse() + + client.get_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_completion_config_rest_bad_request( + request_type=catalog_service.GetCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetCompletionConfigRequest, + dict, + ], +) +def test_get_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetCompletionConfigRequest.pb( + catalog_service.GetCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.GetCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.get_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_completion_config_rest_bad_request( + request_type=catalog_service.UpdateCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCompletionConfigRequest, + dict, + ], +) +def test_update_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + request_init["completion_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", + "matching_order": "matching_order_value", + "max_suggestions": 1632, + "min_prefix_length": 1810, + "auto_learning": True, + "suggestions_input_config": { + "big_query_source": { + "partition_date": {"year": 433, "month": 550, "day": 318}, + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "table_id": "table_id_value", + "gcs_staging_dir": "gcs_staging_dir_value", + "data_schema": "data_schema_value", + } + }, + "last_suggestions_import_operation": "last_suggestions_import_operation_value", + "denylist_input_config": {}, + "last_denylist_import_operation": "last_denylist_import_operation_value", + "allowlist_input_config": {}, + "last_allowlist_import_operation": "last_allowlist_import_operation_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ + "completion_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["completion_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["completion_config"][field])): + del request_init["completion_config"][field][i][subfield] + else: + del request_init["completion_config"][field][subfield] + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCompletionConfigRequest.pb( + catalog_service.UpdateCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.update_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attributes_config_rest_bad_request( + request_type=catalog_service.GetAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetAttributesConfigRequest, + dict, + ], +) +def test_get_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetAttributesConfigRequest.pb( + catalog_service.GetAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.GetAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.get_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attributes_config_rest_bad_request( + request_type=catalog_service.UpdateAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateAttributesConfigRequest, + dict, + ], +) +def test_update_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + request_init["attributes_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", + "catalog_attributes": {}, + "attribute_config_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ + "attributes_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["attributes_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["attributes_config"][field])): + del request_init["attributes_config"][field][i][subfield] + else: + del request_init["attributes_config"][field][subfield] + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateAttributesConfigRequest.pb( + catalog_service.UpdateAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.update_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_catalog_attribute_rest_bad_request( + request_type=catalog_service.AddCatalogAttributeRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_catalog_attribute(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.AddCatalogAttributeRequest, + dict, + ], +) +def test_add_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_catalog_attribute_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_add_catalog_attribute" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.AddCatalogAttributeRequest.pb( + catalog_service.AddCatalogAttributeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.AddCatalogAttributeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.add_catalog_attribute( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_catalog_attribute_rest_bad_request( + request_type=catalog_service.RemoveCatalogAttributeRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_catalog_attribute(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.RemoveCatalogAttributeRequest, + dict, + ], +) +def test_remove_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_catalog_attribute_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( + catalog_service.RemoveCatalogAttributeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.RemoveCatalogAttributeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.remove_catalog_attribute( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_replace_catalog_attribute_rest_bad_request( + request_type=catalog_service.ReplaceCatalogAttributeRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.replace_catalog_attribute(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, + ], +) +def test_replace_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.replace_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_replace_catalog_attribute_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_replace_catalog_attribute" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_replace_catalog_attribute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ReplaceCatalogAttributeRequest.pb( + catalog_service.ReplaceCatalogAttributeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", "body": pb_message, "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value request = catalog_service.ReplaceCatalogAttributeRequest() metadata = [ @@ -8931,19 +9103,77 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): post.assert_called_once() -def test_replace_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ReplaceCatalogAttributeRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -8951,122 +9181,291 @@ def test_replace_catalog_attribute_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.replace_catalog_attribute(request) + client.list_operations(request) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_replace_catalog_attribute_rest_error(): + +def test_initialize_client_w_rest(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + client.update_attributes_config(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CatalogServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + client.remove_catalog_attribute(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -9767,136 +10166,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9924,7 +10193,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -9979,7 +10248,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10026,7 +10295,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -10069,7 +10338,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10124,7 +10393,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10171,7 +10440,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -10187,22 +10456,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_completion_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_completion_service.py index 53343b74e411..dfec5df8bfb4 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_completion_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_completion_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,15 +62,7 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.type import date_pb2 # type: ignore -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.retail_v2.services.completion_service import ( CompletionServiceAsyncClient, @@ -63,10 +72,24 @@ from google.cloud.retail_v2.types import completion_service, import_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1202,25 +1225,6 @@ def test_complete_query(request_type, transport: str = "grpc"): assert response.attribution_token == "attribution_token_value" -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - def test_complete_query_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1294,29 +1298,6 @@ def test_complete_query_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_complete_query_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - ) - response = await client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - @pytest.mark.asyncio async def test_complete_query_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1325,7 +1306,7 @@ async def test_complete_query_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1365,7 +1346,7 @@ async def test_complete_query_async( request_type=completion_service.CompleteQueryRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1431,7 +1412,7 @@ def test_complete_query_field_headers(): @pytest.mark.asyncio async def test_complete_query_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1495,27 +1476,6 @@ def test_import_completion_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - def test_import_completion_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1593,29 +1553,6 @@ def test_import_completion_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_completion_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - @pytest.mark.asyncio async def test_import_completion_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1624,7 +1561,7 @@ async def test_import_completion_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1669,7 +1606,7 @@ async def test_import_completion_data_async( request_type=import_config.ImportCompletionDataRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1736,7 +1673,7 @@ def test_import_completion_data_field_headers(): @pytest.mark.asyncio async def test_import_completion_data_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1767,46 +1704,6 @@ async def test_import_completion_data_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - completion_service.CompleteQueryRequest, - dict, - ], -) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == "attribution_token_value" - - def test_complete_query_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1971,128 +1868,6 @@ def test_complete_query_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" - ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, "pre_complete_query" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb( - completion_service.CompleteQueryRequest() - ) - 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 = completion_service.CompleteQueryResponse.to_json( - completion_service.CompleteQueryResponse() - ) - - request = completion_service.CompleteQueryRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request( - transport: str = "rest", request_type=completion_service.CompleteQueryRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportCompletionDataRequest, - dict, - ], -) -def test_import_completion_data_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_completion_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_completion_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2227,15 +2002,419 @@ def test_import_completion_data_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_completion_data_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CompletionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CompletionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_complete_query_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + ) + await client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_completion_data_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CompletionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_complete_query_rest_bad_request( + request_type=completion_service.CompleteQueryRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.complete_query(request) + + +@pytest.mark.parametrize( + "request_type", + [ + completion_service.CompleteQueryRequest, + dict, + ], +) +def test_complete_query_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == "attribution_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, "pre_complete_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb( + completion_service.CompleteQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = completion_service.CompleteQueryResponse.to_json( + completion_service.CompleteQueryResponse() + ) + req.return_value.content = return_value + + request = completion_service.CompleteQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_completion_data_rest_bad_request( + request_type=import_config.ImportCompletionDataRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_completion_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportCompletionDataRequest, + dict, + ], +) +def test_import_completion_data_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_completion_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_completion_data_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), ) client = CompletionServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -2259,12 +2438,10 @@ def test_import_completion_data_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = import_config.ImportCompletionDataRequest() metadata = [ @@ -2286,17 +2463,17 @@ def test_import_completion_data_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_completion_data_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportCompletionDataRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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( @@ -2304,122 +2481,172 @@ def test_import_completion_data_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.import_completion_data(request) + client.get_operation(request) -def test_import_completion_data_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + response = client.list_operations(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +def test_initialize_client_w_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport + assert client is not None -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CompletionServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + client.import_completion_data(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( + +def test_completion_service_rest_lro_client(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -2659,23 +2886,6 @@ def test_completion_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_completion_service_rest_lro_client(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -3059,136 +3269,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3216,7 +3296,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3271,7 +3351,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3318,7 +3398,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3361,7 +3441,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3416,7 +3496,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3463,7 +3543,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3479,22 +3559,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_control_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_control_service.py index f906e10a0e46..bafcd845cf40 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_control_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_control_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,15 +54,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2.services.control_service import ( ControlServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2.types import control_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1174,25 +1197,6 @@ def test_create_control(request_type, transport: str = "grpc"): ] -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - def test_create_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1258,35 +1262,6 @@ def test_create_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - @pytest.mark.asyncio async def test_create_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1295,7 +1270,7 @@ async def test_create_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1334,7 +1309,7 @@ async def test_create_control_async( transport: str = "grpc_asyncio", request_type=control_service.CreateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1414,7 +1389,7 @@ def test_create_control_field_headers(): @pytest.mark.asyncio async def test_create_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1498,7 +1473,7 @@ def test_create_control_flattened_error(): @pytest.mark.asyncio async def test_create_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1537,7 +1512,7 @@ async def test_create_control_flattened_async(): @pytest.mark.asyncio async def test_create_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1586,25 +1561,6 @@ def test_delete_control(request_type, transport: str = "grpc"): assert response is None -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - def test_delete_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1668,25 +1624,6 @@ def test_delete_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - @pytest.mark.asyncio async def test_delete_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1695,7 +1632,7 @@ async def test_delete_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1734,7 +1671,7 @@ async def test_delete_control_async( transport: str = "grpc_asyncio", request_type=control_service.DeleteControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1795,7 +1732,7 @@ def test_delete_control_field_headers(): @pytest.mark.asyncio async def test_delete_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1863,7 +1800,7 @@ def test_delete_control_flattened_error(): @pytest.mark.asyncio async def test_delete_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1890,7 +1827,7 @@ async def test_delete_control_flattened_async(): @pytest.mark.asyncio async def test_delete_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1952,25 +1889,6 @@ def test_update_control(request_type, transport: str = "grpc"): ] -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - def test_update_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2030,35 +1948,6 @@ def test_update_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - @pytest.mark.asyncio async def test_update_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2067,7 +1956,7 @@ async def test_update_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2106,7 +1995,7 @@ async def test_update_control_async( transport: str = "grpc_asyncio", request_type=control_service.UpdateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2186,7 +2075,7 @@ def test_update_control_field_headers(): @pytest.mark.asyncio async def test_update_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2265,7 +2154,7 @@ def test_update_control_flattened_error(): @pytest.mark.asyncio async def test_update_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2300,7 +2189,7 @@ async def test_update_control_flattened_async(): @pytest.mark.asyncio async def test_update_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2365,25 +2254,6 @@ def test_get_control(request_type, transport: str = "grpc"): ] -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - def test_get_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2447,35 +2317,6 @@ def test_get_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - @pytest.mark.asyncio async def test_get_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2484,7 +2325,7 @@ async def test_get_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2523,7 +2364,7 @@ async def test_get_control_async( transport: str = "grpc_asyncio", request_type=control_service.GetControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2603,7 +2444,7 @@ def test_get_control_field_headers(): @pytest.mark.asyncio async def test_get_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2671,7 +2512,7 @@ def test_get_control_flattened_error(): @pytest.mark.asyncio async def test_get_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2698,7 +2539,7 @@ async def test_get_control_flattened_async(): @pytest.mark.asyncio async def test_get_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2746,25 +2587,6 @@ def test_list_controls(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - def test_list_controls_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2832,29 +2654,6 @@ def test_list_controls_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_controls_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control_service.ListControlsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - @pytest.mark.asyncio async def test_list_controls_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2863,7 +2662,7 @@ async def test_list_controls_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2902,7 +2701,7 @@ async def test_list_controls_async( transport: str = "grpc_asyncio", request_type=control_service.ListControlsRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2968,7 +2767,7 @@ def test_list_controls_field_headers(): @pytest.mark.asyncio async def test_list_controls_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3038,7 +2837,7 @@ def test_list_controls_flattened_error(): @pytest.mark.asyncio async def test_list_controls_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3067,7 +2866,7 @@ async def test_list_controls_flattened_async(): @pytest.mark.asyncio async def test_list_controls_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3177,7 +2976,7 @@ def test_list_controls_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_controls_async_pager(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3227,7 +3026,7 @@ async def test_list_controls_async_pager(): @pytest.mark.asyncio async def test_list_controls_async_pages(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3273,192 +3072,14 @@ async def test_list_controls_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - control_service.CreateControlRequest, - dict, - ], -) -def test_create_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["control"] = { - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "name_value", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = control_service.CreateControlRequest.meta.fields["control"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - - -def test_create_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3595,85 +3216,6 @@ def test_create_control_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_create_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.CreateControlRequest.pb( - control_service.CreateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.CreateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.create_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_control_rest_bad_request( - transport: str = "rest", request_type=control_service.CreateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_control(request) - - def test_create_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3741,61 +3283,18 @@ def test_create_control_rest_flattened_error(transport: str = "rest"): ) -def test_create_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_delete_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - -@pytest.mark.parametrize( - "request_type", - [ - control_service.DeleteControlRequest, - dict, - ], -) -def test_delete_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_control(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.delete_control in client._transport._wrapped_methods @@ -3900,81 +3399,6 @@ def test_delete_control_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" - ) as pre: - pre.assert_not_called() - pb_message = control_service.DeleteControlRequest.pb( - control_service.DeleteControlRequest() - ) - 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() - - request = control_service.DeleteControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_control_rest_bad_request( - transport: str = "rest", request_type=control_service.DeleteControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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.delete_control(request) - - def test_delete_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4032,234 +3456,46 @@ def test_delete_control_rest_flattened_error(transport: str = "rest"): ) -def test_delete_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - control_service.UpdateControlRequest, - dict, - ], -) -def test_update_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.update_control in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - request_init["control"] = { - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_control] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = control_service.UpdateControlRequest.meta.fields["control"] + request = {} + client.update_control(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + client.update_control(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - - -def test_update_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_control in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_control] = mock_rpc - - request = {} - client.update_control(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_control(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_control_rest_required_fields( - request_type=control_service.UpdateControlRequest, -): - transport_class = transports.ControlServiceRestTransport +def test_update_control_rest_required_fields( + request_type=control_service.UpdateControlRequest, +): + transport_class = transports.ControlServiceRestTransport request_init = {} request = request_type(**request_init) @@ -4337,89 +3573,6 @@ def test_update_control_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("control",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_update_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_update_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.UpdateControlRequest.pb( - control_service.UpdateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.UpdateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.update_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_control_rest_bad_request( - transport: str = "rest", request_type=control_service.UpdateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - 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_control(request) - - def test_update_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4487,68 +3640,6 @@ def test_update_control_rest_flattened_error(transport: str = "rest"): ) -def test_update_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.GetControlRequest, - dict, - ], -) -def test_get_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - - def test_get_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4668,89 +3759,8 @@ def test_get_control_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_get_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_get_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.GetControlRequest.pb( - control_service.GetControlRequest() - ) - 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 = control.Control.to_json(control.Control()) - - request = control_service.GetControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = control.Control() - - client.get_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_control_rest_bad_request( - transport: str = "rest", request_type=control_service.GetControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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_control(request) - - -def test_get_control_rest_flattened(): - client = ControlServiceClient( +def test_get_control_rest_flattened(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -4808,52 +3818,6 @@ def test_get_control_rest_flattened_error(transport: str = "rest"): ) -def test_get_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.ListControlsRequest, - dict, - ], -) -def test_list_controls_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = control_service.ListControlsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_controls(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_controls_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4990,87 +3954,6 @@ def test_list_controls_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_controls_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_list_controls" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_list_controls" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.ListControlsRequest.pb( - control_service.ListControlsRequest() - ) - 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 = control_service.ListControlsResponse.to_json( - control_service.ListControlsResponse() - ) - - request = control_service.ListControlsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = control_service.ListControlsResponse() - - client.list_controls( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_controls_rest_bad_request( - transport: str = "rest", request_type=control_service.ListControlsRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_controls(request) - - def test_list_controls_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5220,85 +4103,1475 @@ def test_credentials_transport_error(): transport = transports.ControlServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ControlServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + call.return_value = None + client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + call.return_value = control.Control() + client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ControlServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_controls_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ControlServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_control_rest_bad_request( + request_type=control_service.CreateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.CreateControlRequest, + dict, + ], +) +def test_create_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["control"] = { + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "name_value", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.CreateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_create_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.CreateControlRequest.pb( + control_service.CreateControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value + + request = control_service.CreateControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_control.Control() + + client.create_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_control_rest_bad_request( + request_type=control_service.DeleteControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.DeleteControlRequest, + dict, + ], +) +def test_delete_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_control(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" + ) as pre: + pre.assert_not_called() + pb_message = control_service.DeleteControlRequest.pb( + control_service.DeleteControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = control_service.DeleteControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_control_rest_bad_request( + request_type=control_service.UpdateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.UpdateControlRequest, + dict, + ], +) +def test_update_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + request_init["control"] = { + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.UpdateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_update_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_update_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.UpdateControlRequest.pb( + control_service.UpdateControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value + + request = control_service.UpdateControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_control.Control() + + client.update_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_control_rest_bad_request(request_type=control_service.GetControlRequest): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.GetControlRequest, + dict, + ], +) +def test_get_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_get_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_get_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.GetControlRequest.pb( + control_service.GetControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = control.Control.to_json(control.Control()) + req.return_value.content = return_value + + request = control_service.GetControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = control.Control() + + client.get_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_controls_rest_bad_request( + request_type=control_service.ListControlsRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_controls(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.ListControlsRequest, + dict, + ], +) +def test_list_controls_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = control_service.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_controls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_controls_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_list_controls" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_list_controls" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.ListControlsRequest.pb( + control_service.ListControlsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = control_service.ListControlsResponse.to_json( + control_service.ListControlsResponse() + ) + req.return_value.content = return_value + + request = control_service.ListControlsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = control_service.ListControlsResponse() + + client.list_controls( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + client.delete_control(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ControlServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + client.get_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ControlServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -5923,136 +6196,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6080,7 +6223,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6135,7 +6278,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6182,7 +6325,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6225,7 +6368,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6280,7 +6423,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6327,7 +6470,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6343,22 +6486,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_generative_question_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_generative_question_service.py index a21da9ae519f..4bef2cd68bea 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_generative_question_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_generative_question_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2.services.generative_question_service import ( GenerativeQuestionServiceAsyncClient, @@ -57,10 +66,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1252,30 +1275,6 @@ def test_update_generative_questions_feature_config( assert response.minimum_products == 1743 -def test_update_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - def test_update_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1347,36 +1346,6 @@ def test_update_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1385,7 +1354,7 @@ async def test_update_generative_questions_feature_config_async_use_cached_wrapp # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1425,7 +1394,7 @@ async def test_update_generative_questions_feature_config_async( request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1503,7 +1472,7 @@ def test_update_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1590,7 +1559,7 @@ def test_update_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1629,7 +1598,7 @@ async def test_update_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1688,30 +1657,6 @@ def test_get_generative_questions_feature_config(request_type, transport: str = assert response.minimum_products == 1743 -def test_get_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - def test_get_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1784,36 +1729,6 @@ def test_get_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_get_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1822,7 +1737,7 @@ async def test_get_generative_questions_feature_config_async_use_cached_wrapped_ # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1862,7 +1777,7 @@ async def test_get_generative_questions_feature_config_async( request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1938,7 +1853,7 @@ def test_get_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2012,7 +1927,7 @@ def test_get_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2043,7 +1958,7 @@ async def test_get_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,30 +2009,6 @@ def test_list_generative_question_configs(request_type, transport: str = "grpc") ) -def test_list_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - def test_list_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2190,32 +2081,6 @@ def test_list_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - response = await client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2224,7 +2089,7 @@ async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2264,7 +2129,7 @@ async def test_list_generative_question_configs_async( request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2335,7 +2200,7 @@ def test_list_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_list_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2411,7 +2276,7 @@ def test_list_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2444,7 +2309,7 @@ async def test_list_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2506,30 +2371,6 @@ def test_update_generative_question_config(request_type, transport: str = "grpc" assert response.allowed_in_conversation is True -def test_update_generative_question_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - def test_update_generative_question_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2599,40 +2440,6 @@ def test_update_generative_question_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_question_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - ) - response = await client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_question_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2641,7 +2448,7 @@ async def test_update_generative_question_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2681,7 +2488,7 @@ async def test_update_generative_question_config_async( request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2763,7 +2570,7 @@ def test_update_generative_question_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_question_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2846,7 +2653,7 @@ def test_update_generative_question_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2883,7 +2690,7 @@ async def test_update_generative_question_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2942,30 +2749,6 @@ def test_batch_update_generative_question_configs( ) -def test_batch_update_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - def test_batch_update_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3038,32 +2821,6 @@ def test_batch_update_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_batch_update_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - response = await client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_batch_update_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3072,7 +2829,7 @@ async def test_batch_update_generative_question_configs_async_use_cached_wrapped # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3112,7 +2869,7 @@ async def test_batch_update_generative_question_configs_async( request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3186,7 +2943,7 @@ def test_batch_update_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3285,7 +3042,7 @@ def test_batch_update_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3334,7 +3091,7 @@ async def test_batch_update_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3353,136 +3110,6 @@ async def test_batch_update_generative_question_configs_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_update_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_questions_feature_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "feature_enabled": True, - "minimum_products": 1743, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ - "generative_questions_feature_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_questions_feature_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_questions_feature_config"][field]) - ): - del request_init["generative_questions_feature_config"][field][i][ - subfield - ] - else: - del request_init["generative_questions_feature_config"][field][subfield] - 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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - def test_update_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3617,98 +3244,6 @@ def test_update_generative_questions_feature_config_rest_unset_required_fields() ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.update_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_questions_feature_config(request) - - def test_update_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3780,70 +3315,18 @@ def test_update_generative_questions_feature_config_rest_flattened_error( ) -def test_update_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_get_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - -def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( @@ -3964,96 +3447,6 @@ def test_get_generative_questions_feature_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_get_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_get_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.get_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.get_generative_questions_feature_config(request) - - def test_get_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4117,57 +3510,6 @@ def test_get_generative_questions_feature_config_rest_flattened_error( ) -def test_get_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.ListGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_list_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, generative_question_service.ListGenerativeQuestionConfigsResponse - ) - - def test_list_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4298,132 +3640,42 @@ def test_list_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_list_generative_question_configs_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_list_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_list_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - generative_question_service.ListGenerativeQuestionConfigsRequest() - ) + + # 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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) - request = generative_question_service.ListGenerativeQuestionConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) ) - - client.list_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_generative_question_configs(request) - - -def test_list_generative_question_configs_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value client.list_generative_question_configs(**mock_args) @@ -4453,152 +3705,6 @@ def test_list_generative_question_configs_rest_flattened_error(transport: str = ) -def test_list_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionConfigRequest, - dict, - ], -) -def test_update_generative_question_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_question_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "facet": "facet_value", - "generated_question": "generated_question_value", - "final_question": "final_question_value", - "example_values": ["example_values_value1", "example_values_value2"], - "frequency": 0.978, - "allowed_in_conversation": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ - "generative_question_config" - ] - ) - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_question_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_question_config"][field]) - ): - del request_init["generative_question_config"][field][i][subfield] - else: - del request_init["generative_question_config"][field][subfield] - 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 = generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_question_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionConfig) - assert response.catalog == "catalog_value" - assert response.facet == "facet_value" - assert response.generated_question == "generated_question_value" - assert response.final_question == "final_question_value" - assert response.example_values == ["example_values_value"] - assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) - assert response.allowed_in_conversation is True - - def test_update_generative_question_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4725,108 +3831,16 @@ def test_update_generative_question_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_question_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_update_generative_question_config_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_question_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_question_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionConfig.to_json( - generative_question.GenerativeQuestionConfig() - ) - ) - - request = generative_question_service.UpdateGenerativeQuestionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionConfig() - - client.update_generative_question_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_question_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_question_config(request) - - -def test_update_generative_question_config_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = generative_question.GenerativeQuestionConfig() + # 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 = generative_question.GenerativeQuestionConfig() # get arguments that satisfy an http rule for this method sample_request = { @@ -4886,58 +3900,6 @@ def test_update_generative_question_config_rest_flattened_error( ) -def test_update_generative_question_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_batch_update_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.batch_update_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, - ) - - def test_batch_update_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5070,94 +4032,6 @@ def test_batch_update_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("requests",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_batch_update_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_batch_update_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - 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 = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - request = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - client.batch_update_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.batch_update_generative_question_configs(request) - - def test_batch_update_generative_question_configs_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5239,12 +4113,6 @@ def test_batch_update_generative_question_configs_rest_flattened_error( ) -def test_batch_update_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GenerativeQuestionServiceGrpcTransport( @@ -5278,77 +4146,1477 @@ def test_credentials_transport_error(): transport=transport, ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GenerativeQuestionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GenerativeQuestionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GenerativeQuestionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GenerativeQuestionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GenerativeQuestionServiceGrpcTransport, + transports.GenerativeQuestionServiceGrpcAsyncIOTransport, + transports.GenerativeQuestionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = GenerativeQuestionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionConfig() + client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GenerativeQuestionServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + await client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_question_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + ) + await client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + await client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GenerativeQuestionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_update_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_update_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_questions_feature_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "feature_enabled": True, + "minimum_products": 1743, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ + "generative_questions_feature_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_questions_feature_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_questions_feature_config"][field]) + ): + del request_init["generative_questions_feature_config"][field][i][ + subfield + ] + else: + del request_init["generative_questions_feature_config"][field][subfield] + 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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.update_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_get_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_get_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_get_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.get_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_generative_question_configs_rest_bad_request( + request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.ListGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_list_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, generative_question_service.ListGenerativeQuestionConfigsResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_list_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_list_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + generative_question_service.ListGenerativeQuestionConfigsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + ) + req.return_value.content = return_value + + request = generative_question_service.ListGenerativeQuestionConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + client.list_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_generative_question_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_question_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionConfigRequest, + dict, + ], +) +def test_update_generative_question_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_question_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "facet": "facet_value", + "generated_question": "generated_question_value", + "final_question": "final_question_value", + "example_values": ["example_values_value1", "example_values_value2"], + "frequency": 0.978, + "allowed_in_conversation": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ + "generative_question_config" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_question_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_question_config"][field]) + ): + del request_init["generative_question_config"][field][i][subfield] + else: + del request_init["generative_question_config"][field][subfield] + 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 = generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_question_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionConfig) + assert response.catalog == "catalog_value" + assert response.facet == "facet_value" + assert response.generated_question == "generated_question_value" + assert response.final_question == "final_question_value" + assert response.example_values == ["example_values_value"] + assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) + assert response.allowed_in_conversation is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_question_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_question_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_question_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionConfig.to_json( + generative_question.GenerativeQuestionConfig() + ) + req.return_value.content = return_value + + request = generative_question_service.UpdateGenerativeQuestionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionConfig() + + client.update_generative_question_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_update_generative_question_configs_rest_bad_request( + request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.batch_update_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_batch_update_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_update_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_batch_update_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_batch_update_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + client.batch_update_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() ) - # It is an error to provide scopes and a transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = GenerativeQuestionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() ) + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = GenerativeQuestionServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + client.list_generative_question_configs(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() - transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + client.update_generative_question_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.GenerativeQuestionServiceGrpcTransport, - transports.GenerativeQuestionServiceGrpcAsyncIOTransport, - transports.GenerativeQuestionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = GenerativeQuestionServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -5950,136 +6218,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6107,7 +6245,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6162,7 +6300,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6209,7 +6347,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6252,7 +6390,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6307,7 +6445,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6354,7 +6492,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6370,22 +6508,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_model_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_model_service.py index cf2f0646164d..a41221ad67da 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_model_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_model_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2.services.model_service import ( ModelServiceAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.retail_v2.types import model_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1143,25 +1166,6 @@ def test_create_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - def test_create_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1230,27 +1234,6 @@ def test_create_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - @pytest.mark.asyncio async def test_create_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1259,7 +1242,7 @@ async def test_create_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1303,7 +1286,7 @@ async def test_create_model_async( transport: str = "grpc_asyncio", request_type=model_service.CreateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1349,7 @@ def test_create_model_field_headers(): @pytest.mark.asyncio async def test_create_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1441,7 +1424,7 @@ def test_create_model_flattened_error(): @pytest.mark.asyncio async def test_create_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1474,7 +1457,7 @@ async def test_create_model_flattened_async(): @pytest.mark.asyncio async def test_create_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1547,25 +1530,6 @@ def test_get_model(request_type, transport: str = "grpc"): ) -def test_get_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - def test_get_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1629,45 +1593,13 @@ def test_get_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - @pytest.mark.asyncio async def test_get_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1706,7 +1638,7 @@ async def test_get_model_async( transport: str = "grpc_asyncio", request_type=model_service.GetModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1796,7 +1728,7 @@ def test_get_model_field_headers(): @pytest.mark.asyncio async def test_get_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1864,7 +1796,7 @@ def test_get_model_flattened_error(): @pytest.mark.asyncio async def test_get_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1891,7 +1823,7 @@ async def test_get_model_flattened_async(): @pytest.mark.asyncio async def test_get_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1963,25 +1895,6 @@ def test_pause_model(request_type, transport: str = "grpc"): ) -def test_pause_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - def test_pause_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2045,38 +1958,6 @@ def test_pause_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_pause_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - @pytest.mark.asyncio async def test_pause_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2085,7 +1966,7 @@ async def test_pause_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2124,7 +2005,7 @@ async def test_pause_model_async( transport: str = "grpc_asyncio", request_type=model_service.PauseModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2214,7 +2095,7 @@ def test_pause_model_field_headers(): @pytest.mark.asyncio async def test_pause_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2282,7 +2163,7 @@ def test_pause_model_flattened_error(): @pytest.mark.asyncio async def test_pause_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2309,7 +2190,7 @@ async def test_pause_model_flattened_async(): @pytest.mark.asyncio async def test_pause_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2381,25 +2262,6 @@ def test_resume_model(request_type, transport: str = "grpc"): ) -def test_resume_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - def test_resume_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2463,38 +2325,6 @@ def test_resume_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_resume_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - @pytest.mark.asyncio async def test_resume_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2503,7 +2333,7 @@ async def test_resume_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2542,7 +2372,7 @@ async def test_resume_model_async( transport: str = "grpc_asyncio", request_type=model_service.ResumeModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2632,7 +2462,7 @@ def test_resume_model_field_headers(): @pytest.mark.asyncio async def test_resume_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2700,7 +2530,7 @@ def test_resume_model_flattened_error(): @pytest.mark.asyncio async def test_resume_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2727,7 +2557,7 @@ async def test_resume_model_flattened_async(): @pytest.mark.asyncio async def test_resume_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2772,25 +2602,6 @@ def test_delete_model(request_type, transport: str = "grpc"): assert response is None -def test_delete_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - def test_delete_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2854,25 +2665,6 @@ def test_delete_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - @pytest.mark.asyncio async def test_delete_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2881,7 +2673,7 @@ async def test_delete_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2920,7 +2712,7 @@ async def test_delete_model_async( transport: str = "grpc_asyncio", request_type=model_service.DeleteModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2981,7 +2773,7 @@ def test_delete_model_field_headers(): @pytest.mark.asyncio async def test_delete_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3049,7 +2841,7 @@ def test_delete_model_flattened_error(): @pytest.mark.asyncio async def test_delete_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3076,7 +2868,7 @@ async def test_delete_model_flattened_async(): @pytest.mark.asyncio async def test_delete_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3124,25 +2916,6 @@ def test_list_models(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_models_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - def test_list_models_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3208,29 +2981,6 @@ def test_list_models_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_models_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - @pytest.mark.asyncio async def test_list_models_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3239,7 +2989,7 @@ async def test_list_models_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3278,7 +3028,7 @@ async def test_list_models_async( transport: str = "grpc_asyncio", request_type=model_service.ListModelsRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3344,7 +3094,7 @@ def test_list_models_field_headers(): @pytest.mark.asyncio async def test_list_models_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3414,7 +3164,7 @@ def test_list_models_flattened_error(): @pytest.mark.asyncio async def test_list_models_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3443,7 +3193,7 @@ async def test_list_models_flattened_async(): @pytest.mark.asyncio async def test_list_models_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3553,7 +3303,7 @@ def test_list_models_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_models_async_pager(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3603,7 +3353,7 @@ async def test_list_models_async_pager(): @pytest.mark.asyncio async def test_list_models_async_pages(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3709,25 +3459,6 @@ def test_update_model(request_type, transport: str = "grpc"): ) -def test_update_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - def test_update_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3787,38 +3518,6 @@ def test_update_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - @pytest.mark.asyncio async def test_update_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3827,7 +3526,7 @@ async def test_update_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3866,7 +3565,7 @@ async def test_update_model_async( transport: str = "grpc_asyncio", request_type=model_service.UpdateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3956,7 +3655,7 @@ def test_update_model_field_headers(): @pytest.mark.asyncio async def test_update_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4029,7 +3728,7 @@ def test_update_model_flattened_error(): @pytest.mark.asyncio async def test_update_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4060,7 +3759,7 @@ async def test_update_model_flattened_async(): @pytest.mark.asyncio async def test_update_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4106,25 +3805,6 @@ def test_tune_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_tune_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - def test_tune_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4193,34 +3873,13 @@ def test_tune_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_tune_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - @pytest.mark.asyncio async def test_tune_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4264,7 +3923,7 @@ async def test_tune_model_async( transport: str = "grpc_asyncio", request_type=model_service.TuneModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4327,7 +3986,7 @@ def test_tune_model_field_headers(): @pytest.mark.asyncio async def test_tune_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4397,7 +4056,7 @@ def test_tune_model_flattened_error(): @pytest.mark.asyncio async def test_tune_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4426,7 +4085,7 @@ async def test_tune_model_flattened_async(): @pytest.mark.asyncio async def test_tune_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4438,134 +4097,6 @@ async def test_tune_model_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - model_service.CreateModelRequest, - dict, - ], -) -def test_create_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["model"] = { - "name": "name_value", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1} - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.CreateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4697,93 +4228,10 @@ def test_create_model_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_create_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_create_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_create_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.CreateModelRequest.pb( - model_service.CreateModelRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.CreateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_model_rest_bad_request( - transport: str = "rest", request_type=model_service.CreateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_model(request) - - -def test_create_model_rest_flattened(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -4839,78 +4287,6 @@ def test_create_model_rest_flattened_error(transport: str = "rest"): ) -def test_create_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.GetModelRequest, - dict, - ], -) -def test_get_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_get_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5028,85 +4404,6 @@ def test_get_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_get_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) - 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 = model.Model.to_json(model.Model()) - - request = model_service.GetModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.get_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_model_rest_bad_request( - transport: str = "rest", request_type=model_service.GetModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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_model(request) - - def test_get_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5166,103 +4463,31 @@ def test_get_model_rest_flattened_error(transport: str = "rest"): ) -def test_get_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_pause_model_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - model_service.PauseModelRequest, - dict, - ], -) -def test_pause_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - request = request_type(**request_init) + # Ensure method has been cached + assert client._transport.pause_model in client._transport._wrapped_methods - # 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.pause_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - -def test_pause_model_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.pause_model in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc - - request = {} - client.pause_model(request) + request = {} + client.pause_model(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5356,87 +4581,6 @@ def test_pause_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_pause_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_pause_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.PauseModelRequest.pb( - model_service.PauseModelRequest() - ) - 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 = model.Model.to_json(model.Model()) - - request = model_service.PauseModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.pause_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_pause_model_rest_bad_request( - transport: str = "rest", request_type=model_service.PauseModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.pause_model(request) - - def test_pause_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5496,78 +4640,6 @@ def test_pause_model_rest_flattened_error(transport: str = "rest"): ) -def test_pause_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ResumeModelRequest, - dict, - ], -) -def test_resume_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.resume_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_resume_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5688,108 +4760,27 @@ def test_resume_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_resume_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_resume_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_resume_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ResumeModelRequest.pb( - model_service.ResumeModelRequest() - ) - 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 = model.Model.to_json(model.Model()) + # 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 = model.Model() - request = model_service.ResumeModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } - client.resume_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_resume_model_rest_bad_request( - transport: str = "rest", request_type=model_service.ResumeModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.resume_model(request) - - -def test_resume_model_rest_flattened(): - client = ModelServiceClient( - 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 = model.Model() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -5828,49 +4819,6 @@ def test_resume_model_rest_flattened_error(transport: str = "rest"): ) -def test_resume_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.DeleteModelRequest, - dict, - ], -) -def test_delete_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_model(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5987,81 +4935,6 @@ def test_delete_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" - ) as pre: - pre.assert_not_called() - pb_message = model_service.DeleteModelRequest.pb( - model_service.DeleteModelRequest() - ) - 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() - - request = model_service.DeleteModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_model_rest_bad_request( - transport: str = "rest", request_type=model_service.DeleteModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.delete_model(request) - - def test_delete_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6119,52 +4992,6 @@ def test_delete_model_rest_flattened_error(transport: str = "rest"): ) -def test_delete_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ListModelsRequest, - dict, - ], -) -def test_list_models_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model_service.ListModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_models(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListModelsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_models_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6297,108 +5124,27 @@ def test_list_models_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_models_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_list_models_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_list_models" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ListModelsRequest.pb( - model_service.ListModelsRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = model_service.ListModelsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = model_service.ListModelsResponse.to_json( - model_service.ListModelsResponse() + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - - request = model_service.ListModelsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model_service.ListModelsResponse() - - client.list_models( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_models_rest_bad_request( - transport: str = "rest", request_type=model_service.ListModelsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_models(request) - - -def test_list_models_rest_flattened(): - client = ModelServiceClient( - 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 = model_service.ListModelsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6500,167 +5246,6 @@ def test_list_models_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - model_service.UpdateModelRequest, - dict, - ], -) -def test_update_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - request_init["model"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1} - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.UpdateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == gcr_model.Model.TrainingState.PAUSED - assert response.serving_state == gcr_model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == gcr_model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_update_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6778,99 +5363,16 @@ def test_update_model_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("model",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_update_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_update_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.UpdateModelRequest.pb( - model_service.UpdateModelRequest() - ) - 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 = gcr_model.Model.to_json(gcr_model.Model()) - request = model_service.UpdateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_model.Model() - - client.update_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_model_rest_bad_request( - transport: str = "rest", request_type=model_service.UpdateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - 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_model(request) - - -def test_update_model_rest_flattened(): - client = ModelServiceClient( - 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 = gcr_model.Model() + # 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 = gcr_model.Model() # get arguments that satisfy an http rule for this method sample_request = { @@ -6924,49 +5426,6 @@ def test_update_model_rest_flattened_error(transport: str = "rest"): ) -def test_update_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.TuneModelRequest, - dict, - ], -) -def test_tune_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.tune_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_tune_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7086,89 +5545,6 @@ def test_tune_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_tune_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_tune_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_tune_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.TuneModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.tune_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_tune_model_rest_bad_request( - transport: str = "rest", request_type=model_service.TuneModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.tune_model(request) - - def test_tune_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7226,12 +5602,6 @@ def test_tune_model_rest_flattened_error(transport: str = "rest"): ) -def test_tune_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ModelServiceGrpcTransport( @@ -7273,69 +5643,2029 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.ModelServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ModelServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ModelServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ModelServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ModelServiceGrpcTransport, + transports.ModelServiceGrpcAsyncIOTransport, + transports.ModelServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ModelServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + call.return_value = model.Model() + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + call.return_value = model.Model() + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + call.return_value = model.Model() + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + call.return_value = None + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + call.return_value = model_service.ListModelsResponse() + client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + call.return_value = gcr_model.Model() + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ModelServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_pause_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_resume_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_models_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_tune_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ModelServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_model_rest_bad_request(request_type=model_service.CreateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.CreateModelRequest, + dict, + ], +) +def test_create_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["model"] = { + "name": "name_value", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1} + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.CreateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_create_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_create_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.CreateModelRequest.pb( + model_service.CreateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.CreateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_model_rest_bad_request(request_type=model_service.GetModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.GetModelRequest, + dict, + ], +) +def test_get_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_get_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.GetModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.get_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_pause_model_rest_bad_request(request_type=model_service.PauseModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.pause_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.PauseModelRequest, + dict, + ], +) +def test_pause_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.pause_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_pause_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.PauseModelRequest.pb( + model_service.PauseModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.PauseModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.pause_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resume_model_rest_bad_request(request_type=model_service.ResumeModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.resume_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ResumeModelRequest, + dict, + ], +) +def test_resume_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.resume_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_resume_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ResumeModelRequest.pb( + model_service.ResumeModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.ResumeModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.resume_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_model_rest_bad_request(request_type=model_service.DeleteModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.DeleteModelRequest, + dict, + ], +) +def test_delete_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_model(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" + ) as pre: + pre.assert_not_called() + pb_message = model_service.DeleteModelRequest.pb( + model_service.DeleteModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = model_service.DeleteModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_models_rest_bad_request(request_type=model_service.ListModelsRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_models(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ListModelsRequest, + dict, + ], +) +def test_list_models_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model_service.ListModelsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_models(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListModelsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_models_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_list_models" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ListModelsRequest.pb( + model_service.ListModelsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model_service.ListModelsResponse.to_json( + model_service.ListModelsResponse() + ) + req.return_value.content = return_value + + request = model_service.ListModelsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model_service.ListModelsResponse() + + client.list_models( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_model_rest_bad_request(request_type=model_service.UpdateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.UpdateModelRequest, + dict, + ], +) +def test_update_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + request_init["model"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1} + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.UpdateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == gcr_model.Model.TrainingState.PAUSED + assert response.serving_state == gcr_model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == gcr_model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_update_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.UpdateModelRequest.pb( + model_service.UpdateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_model.Model.to_json(gcr_model.Model()) + req.return_value.content = return_value + + request = model_service.UpdateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_model.Model() + + client.update_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tune_model_rest_bad_request(request_type=model_service.TuneModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.tune_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.TuneModelRequest, + dict, + ], +) +def test_tune_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.tune_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tune_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_tune_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_tune_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.TuneModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.tune_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ModelServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + client.list_models(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ModelServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ModelServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + client.tune_model(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ModelServiceGrpcTransport, - transports.ModelServiceGrpcAsyncIOTransport, - transports.ModelServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ModelServiceClient.get_transport_class(transport_name)( + +def test_model_service_rest_lro_client(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7578,23 +7908,6 @@ def test_model_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_model_service_rest_lro_client(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8017,136 +8330,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8174,7 +8357,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8229,7 +8412,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8276,7 +8459,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8319,7 +8502,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8374,7 +8557,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8421,7 +8604,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8437,22 +8620,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_prediction_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_prediction_service.py index 49827eacf030..2e5e8b050d08 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_prediction_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_prediction_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -38,17 +55,9 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -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.retail_v2.services.prediction_service import ( PredictionServiceAsyncClient, @@ -64,10 +73,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1207,25 +1230,6 @@ def test_predict(request_type, transport: str = "grpc"): assert response.validate_only is True -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - def test_predict_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1293,38 +1297,13 @@ def test_predict_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_predict_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - ) - response = await client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - @pytest.mark.asyncio async def test_predict_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1363,7 +1342,7 @@ async def test_predict_async( transport: str = "grpc_asyncio", request_type=prediction_service.PredictRequest ): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_predict_field_headers(): @pytest.mark.asyncio async def test_predict_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,52 +1441,6 @@ async def test_predict_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - prediction_service.PredictRequest, - dict, - ], -) -def test_predict_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = prediction_service.PredictResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.predict(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == "attribution_token_value" - assert response.missing_ids == ["missing_ids_value"] - assert response.validate_only is True - - def test_predict_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1634,95 +1567,6 @@ def test_predict_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_predict_rest_interceptors(null_interceptor): - transport = transports.PredictionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionServiceRestInterceptor(), - ) - client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" - ) as post, mock.patch.object( - transports.PredictionServiceRestInterceptor, "pre_predict" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_service.PredictRequest.pb( - prediction_service.PredictRequest() - ) - 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 = prediction_service.PredictResponse.to_json( - prediction_service.PredictResponse() - ) - - request = prediction_service.PredictRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = prediction_service.PredictResponse() - - client.predict( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_predict_rest_bad_request( - transport: str = "rest", request_type=prediction_service.PredictRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.predict(request) - - -def test_predict_rest_error(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PredictionServiceGrpcTransport( @@ -1815,80 +1659,425 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = PredictionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request=None) -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + assert args[0] == request_msg -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "predict", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = PredictionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" - ) as Transport: +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_predict_empty_call_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + ) + await client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PredictionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_predict_rest_bad_request(request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.predict(request) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_service.PredictRequest, + dict, + ], +) +def test_predict_rest_call_success(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.predict(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == "attribution_token_value" + assert response.missing_ids == ["missing_ids_value"] + assert response.validate_only is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_predict_rest_interceptors(null_interceptor): + transport = transports.PredictionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionServiceRestInterceptor(), + ) + client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" + ) as post, mock.patch.object( + transports.PredictionServiceRestInterceptor, "pre_predict" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_service.PredictRequest.pb( + prediction_service.PredictRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = prediction_service.PredictResponse.to_json( + prediction_service.PredictResponse() + ) + req.return_value.content = return_value + + request = prediction_service.PredictRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_service.PredictResponse() + + client.predict( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2.services.prediction_service.transports.PredictionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "predict", + "get_operation", + "list_operations", + ) + 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_prediction_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.retail_v2.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionServiceTransport( @@ -2414,136 +2603,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2571,7 +2630,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2626,7 +2685,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2673,7 +2732,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2716,7 +2775,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2771,7 +2830,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2818,7 +2877,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2834,22 +2893,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_product_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_product_service.py index 172a436129c8..aa5ffd33dba3 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_product_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_product_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,17 +64,9 @@ from google.oauth2 import service_account from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2.services.product_service import ( ProductServiceAsyncClient, @@ -71,10 +80,24 @@ from google.cloud.retail_v2.types import product as gcr_product +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1206,25 +1229,6 @@ def test_create_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - def test_create_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,46 +1294,6 @@ def test_create_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - @pytest.mark.asyncio async def test_create_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1338,7 +1302,7 @@ async def test_create_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1377,7 +1341,7 @@ async def test_create_product_async( transport: str = "grpc_asyncio", request_type=product_service.CreateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1477,7 +1441,7 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1559,7 +1523,7 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1596,7 +1560,7 @@ async def test_create_product_flattened_async(): @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1682,25 +1646,6 @@ def test_get_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - def test_get_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1764,46 +1709,6 @@ def test_get_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product.Product( - name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - @pytest.mark.asyncio async def test_get_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1812,7 +1717,7 @@ async def test_get_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1851,7 +1756,7 @@ async def test_get_product_async( transport: str = "grpc_asyncio", request_type=product_service.GetProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1951,7 +1856,7 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2019,7 +1924,7 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1951,7 @@ async def test_get_product_flattened_async(): @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,25 +1999,6 @@ def test_list_products(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - def test_list_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2180,29 +2066,6 @@ def test_list_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - @pytest.mark.asyncio async def test_list_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2211,7 +2074,7 @@ async def test_list_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2250,7 +2113,7 @@ async def test_list_products_async( transport: str = "grpc_asyncio", request_type=product_service.ListProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2316,7 +2179,7 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2386,7 +2249,7 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2415,7 +2278,7 @@ async def test_list_products_flattened_async(): @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2525,7 +2388,7 @@ def test_list_products_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2575,7 +2438,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2691,25 +2554,6 @@ def test_update_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - def test_update_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2769,46 +2613,6 @@ def test_update_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - @pytest.mark.asyncio async def test_update_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2817,7 +2621,7 @@ async def test_update_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2856,7 +2660,7 @@ async def test_update_product_async( transport: str = "grpc_asyncio", request_type=product_service.UpdateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2956,7 +2760,7 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3033,7 +2837,7 @@ def test_update_product_flattened_error(): @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3066,7 +2870,7 @@ async def test_update_product_flattened_async(): @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3114,25 +2918,6 @@ def test_delete_product(request_type, transport: str = "grpc"): assert response is None -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - def test_delete_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3196,25 +2981,6 @@ def test_delete_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - @pytest.mark.asyncio async def test_delete_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3223,7 +2989,7 @@ async def test_delete_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3262,7 +3028,7 @@ async def test_delete_product_async( transport: str = "grpc_asyncio", request_type=product_service.DeleteProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3323,7 +3089,7 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3391,7 +3157,7 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3418,7 +3184,7 @@ async def test_delete_product_flattened_async(): @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3463,25 +3229,6 @@ def test_purge_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - def test_purge_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3552,27 +3299,6 @@ def test_purge_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - @pytest.mark.asyncio async def test_purge_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3581,7 +3307,7 @@ async def test_purge_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3625,7 +3351,7 @@ async def test_purge_products_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3688,7 +3414,7 @@ def test_purge_products_field_headers(): @pytest.mark.asyncio async def test_purge_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3750,25 +3476,6 @@ def test_import_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - def test_import_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3841,27 +3548,6 @@ def test_import_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - @pytest.mark.asyncio async def test_import_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3870,7 +3556,7 @@ async def test_import_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3914,7 +3600,7 @@ async def test_import_products_async( transport: str = "grpc_asyncio", request_type=import_config.ImportProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3977,7 +3663,7 @@ def test_import_products_field_headers(): @pytest.mark.asyncio async def test_import_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4039,25 +3725,6 @@ def test_set_inventory(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - def test_set_inventory_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4122,27 +3789,6 @@ def test_set_inventory_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_inventory_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - @pytest.mark.asyncio async def test_set_inventory_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4151,7 +3797,7 @@ async def test_set_inventory_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4195,7 +3841,7 @@ async def test_set_inventory_async( transport: str = "grpc_asyncio", request_type=product_service.SetInventoryRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4258,7 +3904,7 @@ def test_set_inventory_field_headers(): @pytest.mark.asyncio async def test_set_inventory_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4333,7 +3979,7 @@ def test_set_inventory_flattened_error(): @pytest.mark.asyncio async def test_set_inventory_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4366,7 +4012,7 @@ async def test_set_inventory_flattened_async(): @pytest.mark.asyncio async def test_set_inventory_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4414,27 +4060,6 @@ def test_add_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - def test_add_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4512,29 +4137,6 @@ def test_add_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4543,7 +4145,7 @@ async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4588,7 +4190,7 @@ async def test_add_fulfillment_places_async( request_type=product_service.AddFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4655,7 +4257,7 @@ def test_add_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_add_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4729,7 +4331,7 @@ def test_add_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4760,7 +4362,7 @@ async def test_add_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4807,27 +4409,6 @@ def test_remove_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - def test_remove_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4905,29 +4486,6 @@ def test_remove_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4936,7 +4494,7 @@ async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4981,7 +4539,7 @@ async def test_remove_fulfillment_places_async( request_type=product_service.RemoveFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5048,7 +4606,7 @@ def test_remove_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_remove_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5122,7 +4680,7 @@ def test_remove_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5153,7 +4711,7 @@ async def test_remove_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5200,27 +4758,6 @@ def test_add_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - def test_add_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5296,29 +4833,6 @@ def test_add_local_inventories_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - @pytest.mark.asyncio async def test_add_local_inventories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5327,7 +4841,7 @@ async def test_add_local_inventories_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5372,7 +4886,7 @@ async def test_add_local_inventories_async( request_type=product_service.AddLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5439,7 +4953,7 @@ def test_add_local_inventories_field_headers(): @pytest.mark.asyncio async def test_add_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5513,7 +5027,7 @@ def test_add_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5544,7 +5058,7 @@ async def test_add_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5591,27 +5105,6 @@ def test_remove_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - def test_remove_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5688,39 +5181,16 @@ def test_remove_local_inventories_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_remove_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - -@pytest.mark.asyncio -async def test_remove_local_inventories_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_remove_local_inventories_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -5763,7 +5233,7 @@ async def test_remove_local_inventories_async( request_type=product_service.RemoveLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5830,7 +5300,7 @@ def test_remove_local_inventories_field_headers(): @pytest.mark.asyncio async def test_remove_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5904,7 +5374,7 @@ def test_remove_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5935,7 +5405,7 @@ async def test_remove_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5947,229 +5417,6 @@ async def test_remove_local_inventories_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - product_service.CreateProductRequest, - dict, - ], -) -def test_create_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = product_service.CreateProductRequest.meta.fields["product"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] - 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - def test_create_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6314,89 +5561,8 @@ def test_create_product_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_create_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.CreateProductRequest.pb( - product_service.CreateProductRequest() - ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) - - request = product_service.CreateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() - - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_product_rest_bad_request( - transport: str = "rest", request_type=product_service.CreateProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.create_product(request) - - -def test_create_product_rest_flattened(): - client = ProductServiceClient( +def test_create_product_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -6462,88 +5628,6 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): ) -def test_create_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.GetProductRequest, - dict, - ], -) -def test_get_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = product.Product( - name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - def test_get_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6663,87 +5747,6 @@ def test_get_product_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_get_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.GetProductRequest.pb( - product_service.GetProductRequest() - ) - 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 = product.Product.to_json(product.Product()) - - request = product_service.GetProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product.Product() - - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_product_rest_bad_request( - transport: str = "rest", request_type=product_service.GetProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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_product(request) - - def test_get_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6803,69 +5806,21 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): ) -def test_get_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_list_products_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - product_service.ListProductsRequest, - dict, - ], -) -def test_list_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = product_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product_service.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_products(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_products_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_products in client._transport._wrapped_methods + # Ensure method has been cached + assert client._transport.list_products in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -6989,89 +5944,6 @@ def test_list_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_list_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.ListProductsRequest.pb( - product_service.ListProductsRequest() - ) - 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 = product_service.ListProductsResponse.to_json( - product_service.ListProductsResponse() - ) - - request = product_service.ListProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product_service.ListProductsResponse() - - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_products_rest_bad_request( - transport: str = "rest", request_type=product_service.ListProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.list_products(request) - - def test_list_products_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7196,256 +6068,31 @@ def test_list_products_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - product_service.UpdateProductRequest, - dict, - ], -) -def test_update_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = product_service.UpdateProductRequest.meta.fields["product"] + # Ensure method has been cached + assert client._transport.update_product in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_product] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] - 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - -def test_update_product_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_product] = mock_rpc - - request = {} - client.update_product(request) + request = {} + client.update_product(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7551,89 +6198,6 @@ def test_update_product_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_update_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.UpdateProductRequest.pb( - product_service.UpdateProductRequest() - ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) - - request = product_service.UpdateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() - - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_product_rest_bad_request( - transport: str = "rest", request_type=product_service.UpdateProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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_product(request) - - def test_update_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7701,49 +6265,6 @@ def test_update_product_rest_flattened_error(transport: str = "rest"): ) -def test_update_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_product(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7860,81 +6381,6 @@ def test_delete_product_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "pre_delete_product" - ) as pre: - pre.assert_not_called() - pb_message = product_service.DeleteProductRequest.pb( - product_service.DeleteProductRequest() - ) - 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() - - request = product_service.DeleteProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_product_rest_bad_request( - transport: str = "rest", request_type=product_service.DeleteProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.delete_product(request) - - def test_delete_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7992,49 +6438,6 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): ) -def test_delete_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeProductsRequest, - dict, - ], -) -def test_purge_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_purge_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8168,134 +6571,6 @@ def test_purge_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_purge_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_purge_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeProductsRequest.pb( - purge_config.PurgeProductsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = purge_config.PurgeProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_products_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.purge_products(request) - - -def test_purge_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportProductsRequest, - dict, - ], -) -def test_import_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8425,136 +6700,6 @@ def test_import_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_import_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_import_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportProductsRequest.pb( - import_config.ImportProductsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = import_config.ImportProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_products_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.import_products(request) - - -def test_import_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.SetInventoryRequest, - dict, - ], -) -def test_set_inventory_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_inventory(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_set_inventory_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8671,93 +6816,6 @@ def test_set_inventory_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("inventory",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_inventory_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_set_inventory" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_set_inventory" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.SetInventoryRequest.pb( - product_service.SetInventoryRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.SetInventoryRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_inventory( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_inventory_rest_bad_request( - transport: str = "rest", request_type=product_service.SetInventoryRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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.set_inventory(request) - - def test_set_inventory_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8819,49 +6877,6 @@ def test_set_inventory_rest_flattened_error(transport: str = "rest"): ) -def test_set_inventory_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.AddFulfillmentPlacesRequest, - dict, - ], -) -def test_add_fulfillment_places_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_add_fulfillment_places_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9005,95 +7020,10 @@ def test_add_fulfillment_places_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_fulfillment_places_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_add_fulfillment_places_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_add_fulfillment_places" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_add_fulfillment_places" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.AddFulfillmentPlacesRequest.pb( - product_service.AddFulfillmentPlacesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.AddFulfillmentPlacesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.add_fulfillment_places( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.AddFulfillmentPlacesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.add_fulfillment_places(request) - - -def test_add_fulfillment_places_rest_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -9147,49 +7077,6 @@ def test_add_fulfillment_places_rest_flattened_error(transport: str = "rest"): ) -def test_add_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.RemoveFulfillmentPlacesRequest, - dict, - ], -) -def test_remove_fulfillment_places_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_remove_fulfillment_places_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9333,91 +7220,6 @@ def test_remove_fulfillment_places_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_fulfillment_places_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_remove_fulfillment_places" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_remove_fulfillment_places" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.RemoveFulfillmentPlacesRequest.pb( - product_service.RemoveFulfillmentPlacesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.RemoveFulfillmentPlacesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.remove_fulfillment_places( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_remove_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveFulfillmentPlacesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.remove_fulfillment_places(request) - - def test_remove_fulfillment_places_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9475,49 +7277,6 @@ def test_remove_fulfillment_places_rest_flattened_error(transport: str = "rest") ) -def test_remove_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.AddLocalInventoriesRequest, - dict, - ], -) -def test_add_local_inventories_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_local_inventories(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_add_local_inventories_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9652,101 +7411,16 @@ def test_add_local_inventories_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_local_inventories_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_add_local_inventories_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), + transport="rest", ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_add_local_inventories" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_add_local_inventories" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.AddLocalInventoriesRequest.pb( - product_service.AddLocalInventoriesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.AddLocalInventoriesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.add_local_inventories( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.AddLocalInventoriesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.add_local_inventories(request) - - -def test_add_local_inventories_rest_flattened(): - client = ProductServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") + # 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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -9794,49 +7468,6 @@ def test_add_local_inventories_rest_flattened_error(transport: str = "rest"): ) -def test_add_local_inventories_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.RemoveLocalInventoriesRequest, - dict, - ], -) -def test_remove_local_inventories_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_local_inventories(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_remove_local_inventories_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9975,91 +7606,6 @@ def test_remove_local_inventories_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_local_inventories_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_remove_local_inventories" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.RemoveLocalInventoriesRequest.pb( - product_service.RemoveLocalInventoriesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.RemoveLocalInventoriesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.remove_local_inventories( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_remove_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveLocalInventoriesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.remove_local_inventories(request) - - def test_remove_local_inventories_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10117,12 +7663,6 @@ def test_remove_local_inventories_rest_flattened_error(transport: str = "rest"): ) -def test_remove_local_inventories_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProductServiceGrpcTransport( @@ -10175,58 +7715,2935 @@ def test_credentials_transport_error(): ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProductServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + call.return_value = product.Product() + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + call.return_value = None + client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProductServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_inventory_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProductServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_product_rest_bad_request( + request_type=product_service.CreateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.CreateProductRequest, + dict, + ], +) +def test_create_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.CreateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_create_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.CreateProductRequest.pb( + product_service.CreateProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value + + request = product_service.CreateProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_product.Product() + + client.create_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_product_rest_bad_request(request_type=product_service.GetProductRequest): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.GetProductRequest, + dict, + ], +) +def test_get_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_get_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.GetProductRequest.pb( + product_service.GetProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product.Product.to_json(product.Product()) + req.return_value.content = return_value + + request = product_service.GetProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product.Product() + + client.get_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_products_rest_bad_request( + request_type=product_service.ListProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.ListProductsRequest, + dict, + ], +) +def test_list_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = product_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product_service.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_list_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.ListProductsRequest.pb( + product_service.ListProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product_service.ListProductsResponse.to_json( + product_service.ListProductsResponse() + ) + req.return_value.content = return_value + + request = product_service.ListProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product_service.ListProductsResponse() + + client.list_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_product_rest_bad_request( + request_type=product_service.UpdateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.UpdateProductRequest, + dict, + ], +) +def test_update_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.UpdateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_update_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_update_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.UpdateProductRequest.pb( + product_service.UpdateProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value + + request = product_service.UpdateProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_product.Product() + + client.update_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_product_rest_bad_request( + request_type=product_service.DeleteProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.DeleteProductRequest, + dict, + ], +) +def test_delete_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_product(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "pre_delete_product" + ) as pre: + pre.assert_not_called() + pb_message = product_service.DeleteProductRequest.pb( + product_service.DeleteProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = product_service.DeleteProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_purge_products_rest_bad_request( + request_type=purge_config.PurgeProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeProductsRequest, + dict, + ], +) +def test_purge_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_products(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_purge_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_purge_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeProductsRequest.pb( + purge_config.PurgeProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = purge_config.PurgeProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_products_rest_bad_request( + request_type=import_config.ImportProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportProductsRequest, + dict, + ], +) +def test_import_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_products(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_import_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_import_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportProductsRequest.pb( + import_config.ImportProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = import_config.ImportProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_inventory_rest_bad_request( + request_type=product_service.SetInventoryRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_inventory(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.SetInventoryRequest, + dict, + ], +) +def test_set_inventory_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_inventory(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_inventory_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_set_inventory" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_set_inventory" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.SetInventoryRequest.pb( + product_service.SetInventoryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.SetInventoryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.set_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_fulfillment_places_rest_bad_request( + request_type=product_service.AddFulfillmentPlacesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_fulfillment_places(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.AddFulfillmentPlacesRequest, + dict, + ], +) +def test_add_fulfillment_places_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_fulfillment_places(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_fulfillment_places_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_add_fulfillment_places" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_add_fulfillment_places" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.AddFulfillmentPlacesRequest.pb( + product_service.AddFulfillmentPlacesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.AddFulfillmentPlacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_fulfillment_places( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_fulfillment_places_rest_bad_request( + request_type=product_service.RemoveFulfillmentPlacesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_fulfillment_places(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.RemoveFulfillmentPlacesRequest, + dict, + ], +) +def test_remove_fulfillment_places_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_fulfillment_places(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_fulfillment_places_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_remove_fulfillment_places" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_remove_fulfillment_places" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.RemoveFulfillmentPlacesRequest.pb( + product_service.RemoveFulfillmentPlacesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.RemoveFulfillmentPlacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_fulfillment_places( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_local_inventories_rest_bad_request( + request_type=product_service.AddLocalInventoriesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_local_inventories(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.AddLocalInventoriesRequest, + dict, + ], +) +def test_add_local_inventories_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_local_inventories(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_local_inventories_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_add_local_inventories" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_add_local_inventories" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.AddLocalInventoriesRequest.pb( + product_service.AddLocalInventoriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.AddLocalInventoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_local_inventories_rest_bad_request( + request_type=product_service.RemoveLocalInventoriesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_local_inventories(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.RemoveLocalInventoriesRequest, + dict, + ], +) +def test_remove_local_inventories_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_local_inventories(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_local_inventories_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_remove_local_inventories" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.RemoveLocalInventoriesRequest.pb( + product_service.RemoveLocalInventoriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.RemoveLocalInventoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + client.remove_fulfillment_places(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ProductServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + client.remove_local_inventories(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProductServiceClient.get_transport_class(transport_name)( + +def test_product_service_rest_lro_client(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -10476,23 +10893,6 @@ def test_product_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_product_service_rest_lro_client(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -10943,136 +11343,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11100,7 +11370,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11155,7 +11425,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11202,7 +11472,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -11245,7 +11515,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11300,7 +11570,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11347,7 +11617,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -11363,22 +11633,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_search_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_search_service.py index 55f2965a2e75..ccaa0772250a 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_search_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_search_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,14 +53,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2.services.search_service import ( SearchServiceAsyncClient, @@ -54,10 +63,24 @@ from google.cloud.retail_v2.types import common, search_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1161,25 +1184,6 @@ def test_search(request_type, transport: str = "grpc"): assert response.applied_controls == ["applied_controls_value"] -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - def test_search_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1259,41 +1263,13 @@ def test_search_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - ) - response = await client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - @pytest.mark.asyncio async def test_search_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1332,7 +1308,7 @@ async def test_search_async( transport: str = "grpc_asyncio", request_type=search_service.SearchRequest ): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1408,7 +1384,7 @@ def test_search_field_headers(): @pytest.mark.asyncio async def test_search_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1537,7 +1513,7 @@ def test_search_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_async_pager(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1565,7 @@ async def test_search_async_pager(): @pytest.mark.asyncio async def test_search_async_pages(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,58 +1609,6 @@ async def test_search_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - search_service.SearchRequest, - dict, - ], -) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == "corrected_query_value" - assert response.attribution_token == "attribution_token_value" - assert response.next_page_token == "next_page_token_value" - assert response.redirect_uri == "redirect_uri_value" - assert response.applied_controls == ["applied_controls_value"] - - def test_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1815,87 +1739,6 @@ def test_search_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" - ) as post, mock.patch.object( - transports.SearchServiceRestInterceptor, "pre_search" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - 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 = search_service.SearchResponse.to_json( - search_service.SearchResponse() - ) - - request = search_service.SearchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request( - transport: str = "rest", request_type=search_service.SearchRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.search(request) - - def test_search_rest_pager(transport: str = "rest"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2053,76 +1896,428 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = SearchServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + call.return_value = search_service.SearchResponse() + client.search(request=None) -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + assert args[0] == request_msg -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "search", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = SearchServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_empty_call_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + ) + await client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SearchServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_rest_bad_request(request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search(request) + + +@pytest.mark.parametrize( + "request_type", + [ + search_service.SearchRequest, + dict, + ], +) +def test_search_rest_call_success(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == "corrected_query_value" + assert response.attribution_token == "attribution_token_value" + assert response.next_page_token == "next_page_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.applied_controls == ["applied_controls_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" + ) as post, mock.patch.object( + transports.SearchServiceRestInterceptor, "pre_search" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = search_service.SearchResponse.to_json( + search_service.SearchResponse() + ) + req.return_value.content = return_value + + request = search_service.SearchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2.services.search_service.transports.SearchServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search", + "get_operation", + "list_operations", + ) + 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_search_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.retail_v2.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages" @@ -2739,136 +2934,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2896,7 +2961,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2951,7 +3016,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2998,7 +3063,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3041,7 +3106,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3096,7 +3161,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3143,7 +3208,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3159,22 +3224,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_serving_config_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_serving_config_service.py index 290585ccfe20..207bbaae739d 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_serving_config_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_serving_config_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2.services.serving_config_service import ( ServingConfigServiceAsyncClient, @@ -58,10 +67,24 @@ from google.cloud.retail_v2.types import serving_config_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1268,27 +1291,6 @@ def test_create_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - def test_create_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1361,48 +1363,6 @@ def test_create_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - @pytest.mark.asyncio async def test_create_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1411,7 +1371,7 @@ async def test_create_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1451,7 +1411,7 @@ async def test_create_serving_config_async( request_type=serving_config_service.CreateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1560,7 +1520,7 @@ def test_create_serving_config_field_headers(): @pytest.mark.asyncio async def test_create_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1644,7 +1604,7 @@ def test_create_serving_config_flattened_error(): @pytest.mark.asyncio async def test_create_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1683,7 +1643,7 @@ async def test_create_serving_config_flattened_async(): @pytest.mark.asyncio async def test_create_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1732,27 +1692,6 @@ def test_delete_serving_config(request_type, transport: str = "grpc"): assert response is None -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - def test_delete_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1823,27 +1762,6 @@ def test_delete_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - @pytest.mark.asyncio async def test_delete_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1852,7 +1770,7 @@ async def test_delete_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1892,7 +1810,7 @@ async def test_delete_serving_config_async( request_type=serving_config_service.DeleteServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1957,7 +1875,7 @@ def test_delete_serving_config_field_headers(): @pytest.mark.asyncio async def test_delete_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2029,7 +1947,7 @@ def test_delete_serving_config_flattened_error(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2058,7 +1976,7 @@ async def test_delete_serving_config_flattened_async(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2147,27 +2065,6 @@ def test_update_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - def test_update_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2234,48 +2131,6 @@ def test_update_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - @pytest.mark.asyncio async def test_update_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2284,7 +2139,7 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2324,7 +2179,7 @@ async def test_update_serving_config_async( request_type=serving_config_service.UpdateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2433,7 +2288,7 @@ def test_update_serving_config_field_headers(): @pytest.mark.asyncio async def test_update_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2512,7 +2367,7 @@ def test_update_serving_config_flattened_error(): @pytest.mark.asyncio async def test_update_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2547,7 +2402,7 @@ async def test_update_serving_config_flattened_async(): @pytest.mark.asyncio async def test_update_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2637,27 +2492,6 @@ def test_get_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - def test_get_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2727,48 +2561,6 @@ def test_get_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - @pytest.mark.asyncio async def test_get_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2777,7 +2569,7 @@ async def test_get_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2817,7 +2609,7 @@ async def test_get_serving_config_async( request_type=serving_config_service.GetServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2926,7 +2718,7 @@ def test_get_serving_config_field_headers(): @pytest.mark.asyncio async def test_get_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3000,7 +2792,7 @@ def test_get_serving_config_flattened_error(): @pytest.mark.asyncio async def test_get_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3031,7 +2823,7 @@ async def test_get_serving_config_flattened_async(): @pytest.mark.asyncio async def test_get_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3081,27 +2873,6 @@ def test_list_serving_configs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - def test_list_serving_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3173,31 +2944,6 @@ def test_list_serving_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_serving_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - @pytest.mark.asyncio async def test_list_serving_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3206,7 +2952,7 @@ async def test_list_serving_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3246,7 +2992,7 @@ async def test_list_serving_configs_async( request_type=serving_config_service.ListServingConfigsRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3316,7 +3062,7 @@ def test_list_serving_configs_field_headers(): @pytest.mark.asyncio async def test_list_serving_configs_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3390,7 +3136,7 @@ def test_list_serving_configs_flattened_error(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3421,7 +3167,7 @@ async def test_list_serving_configs_flattened_async(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3535,7 +3281,7 @@ def test_list_serving_configs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_serving_configs_async_pager(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3587,7 +3333,7 @@ async def test_list_serving_configs_async_pager(): @pytest.mark.asyncio async def test_list_serving_configs_async_pages(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3710,25 +3456,6 @@ def test_add_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - def test_add_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3794,46 +3521,6 @@ def test_add_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - @pytest.mark.asyncio async def test_add_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3842,7 +3529,7 @@ async def test_add_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3882,7 +3569,7 @@ async def test_add_control_async( request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3987,7 +3674,7 @@ def test_add_control_field_headers(): @pytest.mark.asyncio async def test_add_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4057,7 +3744,7 @@ def test_add_control_flattened_error(): @pytest.mark.asyncio async def test_add_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4086,7 +3773,7 @@ async def test_add_control_flattened_async(): @pytest.mark.asyncio async def test_add_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4173,25 +3860,6 @@ def test_remove_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - def test_remove_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4257,46 +3925,6 @@ def test_remove_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - @pytest.mark.asyncio async def test_remove_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4305,7 +3933,7 @@ async def test_remove_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4345,7 +3973,7 @@ async def test_remove_control_async( request_type=serving_config_service.RemoveControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4450,7 +4078,7 @@ def test_remove_control_field_headers(): @pytest.mark.asyncio async def test_remove_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4520,7 +4148,7 @@ def test_remove_control_flattened_error(): @pytest.mark.asyncio async def test_remove_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4549,7 +4177,7 @@ async def test_remove_control_flattened_async(): @pytest.mark.asyncio async def test_remove_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4561,236 +4189,45 @@ async def test_remove_control_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.CreateServingConfigRequest, - dict, - ], -) -def test_create_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["serving_config"] = { - "name": "name_value", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ - "serving_config" - ] + # Ensure method has been cached + assert ( + client._transport.create_serving_config + in client._transport._wrapped_methods + ) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_serving_config + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_serving_config(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.create_serving_config(request) - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_serving_config - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_serving_config - ] = mock_rpc - - request = {} - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_serving_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 def test_create_serving_config_rest_required_fields( @@ -4901,88 +4338,6 @@ def test_create_serving_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.CreateServingConfigRequest.pb( - serving_config_service.CreateServingConfigRequest() - ) - 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 = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() - ) - - request = serving_config_service.CreateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() - - client.create_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.CreateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_serving_config(request) - - def test_create_serving_config_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5046,49 +4401,6 @@ def test_create_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_create_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.DeleteServingConfigRequest, - dict, - ], -) -def test_delete_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_serving_config(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5210,84 +4522,8 @@ def test_delete_serving_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" - ) as pre: - pre.assert_not_called() - pb_message = serving_config_service.DeleteServingConfigRequest.pb( - serving_config_service.DeleteServingConfigRequest() - ) - 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() - - request = serving_config_service.DeleteServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.DeleteServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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.delete_serving_config(request) - - -def test_delete_serving_config_rest_flattened(): - client = ServingConfigServiceClient( +def test_delete_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -5343,168 +4579,152 @@ def test_delete_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_delete_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_serving_config + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_serving_config + ] = mock_rpc + + request = {} + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_serving_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_serving_config_rest_required_fields( + request_type=serving_config_service.UpdateServingConfigRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_serving_config._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_serving_config._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 -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.UpdateServingConfigRequest, - dict, - ], -) -def test_update_serving_config_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - request_init["serving_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ - "serving_config" - ] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.update_serving_config(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_serving_config_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.update_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - request = request_type(**request_init) + +def test_update_serving_config_rest_flattened(): + client = ServingConfigServiceClient( + 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + return_value = gcr_serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + serving_config=gcr_serving_config.ServingConfig(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() @@ -5512,39 +4732,39 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + client.update_serving_config(**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/v2/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_serving_config_rest_flattened_error(transport: str = "rest"): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_update_serving_config_rest_use_cached_wrapped_rpc(): +def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5559,8 +4779,7 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_serving_config - in client._transport._wrapped_methods + client._transport.get_serving_config in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5569,28 +4788,29 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_serving_config + client._transport.get_serving_config ] = mock_rpc request = {} - client.update_serving_config(request) + client.get_serving_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_serving_config(request) + client.get_serving_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_serving_config_rest_required_fields( - request_type=serving_config_service.UpdateServingConfigRequest, +def test_get_serving_config_rest_required_fields( + request_type=serving_config_service.GetServingConfigRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5601,19 +4821,21 @@ def test_update_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_serving_config._get_unset_required_fields(jsonified_request) + ).get_serving_config._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() - ).update_serving_config._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",)) + ).get_serving_config._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 = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5622,7 +4844,7 @@ def test_update_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() + return_value = serving_config.ServingConfig() # 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 @@ -5634,172 +4856,82 @@ def test_update_serving_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) + response = client.get_serving_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_serving_config_rest_unset_required_fields(): +def test_get_serving_config_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) + unset_fields = transport.get_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_get_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.UpdateServingConfigRequest.pb( - serving_config_service.UpdateServingConfigRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - request = serving_config_service.UpdateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.update_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_serving_config(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) -def test_update_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.UpdateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - 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_serving_config(request) - - -def test_update_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config=gcr_serving_config.ServingConfig(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 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_serving_config(**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/v2/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" - % client.transport._host, - args[1], - ) - - -def test_update_serving_config_rest_flattened_error(transport: str = "rest"): +def test_get_serving_config_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5808,101 +4940,13 @@ def test_update_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.GetServingConfigRequest, - dict, - ], -) -def test_get_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = serving_config.ServingConfig( + client.get_serving_config( + serving_config_service.GetServingConfigRequest(), name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - -def test_get_serving_config_rest_use_cached_wrapped_rpc(): +def test_list_serving_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5917,7 +4961,7 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_serving_config in client._transport._wrapped_methods + client._transport.list_serving_configs in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5926,29 +4970,29 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_serving_config + client._transport.list_serving_configs ] = mock_rpc request = {} - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_serving_config_rest_required_fields( - request_type=serving_config_service.GetServingConfigRequest, +def test_list_serving_configs_rest_required_fields( + request_type=serving_config_service.ListServingConfigsRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5959,21 +5003,28 @@ def test_get_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5982,7 +5033,7 @@ def test_get_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse() # 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 @@ -6003,130 +5054,57 @@ def test_get_serving_config_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_serving_config(request) + response = client.list_serving_configs(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_serving_config_rest_unset_required_fields(): +def test_list_serving_configs_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_list_serving_configs_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_get_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.GetServingConfigRequest.pb( - serving_config_service.GetServingConfigRequest() - ) - 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 = serving_config.ServingConfig.to_json( - serving_config.ServingConfig() - ) - - request = serving_config_service.GetServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config.ServingConfig() - - client.get_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_serving_config_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.GetServingConfigRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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_serving_config(request) - - -def test_get_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = serving_config.ServingConfig() + # 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 = serving_config_service.ListServingConfigsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -6134,25 +5112,27 @@ def test_get_serving_config_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_serving_config(**mock_args) + client.list_serving_configs(**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/v2/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + "%s/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" % client.transport._host, args[1], ) -def test_get_serving_config_rest_flattened_error(transport: str = "rest"): +def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6161,61 +5141,79 @@ def test_get_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_serving_config( - serving_config_service.GetServingConfigRequest(), - name="name_value", + client.list_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent="parent_value", ) -def test_get_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.ListServingConfigsRequest, - dict, - ], -) -def test_list_serving_configs_rest(request_type): +def test_list_serving_configs_rest_pager(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token="abc", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token="def", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token="ghi", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), ) + # Two responses for two calls + response = response + response - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value + # Wrap the values into proper Response objs + response = tuple( + serving_config_service.ListServingConfigsResponse.to_json(x) + for x in response ) - json_return_value = json_format.MessageToJson(return_value) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_serving_configs(request) + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == "next_page_token_value" + pager = client.list_serving_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) for i in results) + + pages = list(client.list_serving_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_serving_configs_rest_use_cached_wrapped_rpc(): +def test_add_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6229,39 +5227,36 @@ def test_list_serving_configs_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_serving_configs in client._transport._wrapped_methods - ) + assert client._transport.add_control in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_serving_configs - ] = mock_rpc + client._transport._wrapped_methods[client._transport.add_control] = mock_rpc request = {} - client.list_serving_configs(request) + client.add_control(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_serving_configs(request) + client.add_control(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_serving_configs_rest_required_fields( - request_type=serving_config_service.ListServingConfigsRequest, +def test_add_control_rest_required_fields( + request_type=serving_config_service.AddControlRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6272,28 +5267,24 @@ def test_list_serving_configs_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) + ).add_control._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" + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).add_control._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" + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6302,7 +5293,7 @@ def test_list_serving_configs_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # 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 @@ -6314,132 +5305,238 @@ def test_list_serving_configs_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_serving_configs(request) + response = client.add_control(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_serving_configs_rest_unset_required_fields(): +def test_add_control_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + unset_fields = transport.add_control._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "servingConfig", + "controlId", ) ) - & set(("parent",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_serving_configs_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_add_control_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_list_serving_configs" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.ListServingConfigsRequest.pb( - serving_config_service.ListServingConfigsRequest() - ) - 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 = ( - serving_config_service.ListServingConfigsResponse.to_json( - serving_config_service.ListServingConfigsResponse() - ) - ) + # 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 = gcr_serving_config.ServingConfig() - request = serving_config_service.ListServingConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config_service.ListServingConfigsResponse() + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } - client.list_serving_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + serving_config="serving_config_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + client.add_control(**mock_args) -def test_list_serving_configs_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.ListServingConfigsRequest, -): + # 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/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" + % client.transport._host, + args[1], + ) + + +def test_add_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config="serving_config_value", + ) + + +def test_remove_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_control in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + + request = {} + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_control(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_control_rest_required_fields( + request_type=serving_config_service.RemoveControlRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # 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.list_serving_configs(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_list_serving_configs_rest_flattened(): + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" + + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.remove_control(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_control_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_control._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "servingConfig", + "controlId", + ) + ) + ) + + +def test_remove_control_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6448,16 +5545,16 @@ def test_list_serving_configs_rest_flattened(): # 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 = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + serving_config="serving_config_value", ) mock_args.update(sample_request) @@ -6465,27 +5562,25 @@ def test_list_serving_configs_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_serving_configs(**mock_args) + client.remove_control(**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/v2/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" + "%s/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" % client.transport._host, args[1], ) -def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): +def test_remove_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6494,101 +5589,1286 @@ def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent="parent_value", + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config="serving_config_value", ) -def test_list_serving_configs_rest_pager(transport: str = "rest"): - client = ServingConfigServiceClient( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token="abc", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token="def", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token="ghi", - ), + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ServingConfigServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + call.return_value = None + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ServingConfigServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_serving_configs_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), + next_page_token="next_page_token_value", + ) + ) + await client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ServingConfigServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_serving_config_rest_bad_request( + request_type=serving_config_service.CreateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.CreateServingConfigRequest, + dict, + ], +) +def test_create_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["serving_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.CreateServingConfigRequest.pb( + serving_config_service.CreateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.CreateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.create_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_serving_config_rest_bad_request( + request_type=serving_config_service.DeleteServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.DeleteServingConfigRequest, + dict, + ], +) +def test_delete_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_serving_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" + ) as pre: + pre.assert_not_called() + pb_message = serving_config_service.DeleteServingConfigRequest.pb( + serving_config_service.DeleteServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = serving_config_service.DeleteServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_serving_config_rest_bad_request( + request_type=serving_config_service.UpdateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.UpdateServingConfigRequest, + dict, + ], +) +def test_update_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + request_init["serving_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - serving_config_service.ListServingConfigsResponse.to_json(x) - for x in response + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.UpdateServingConfigRequest.pb( + serving_config_service.UpdateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.UpdateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.update_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } + pre.assert_called_once() + post.assert_called_once() - pager = client.list_serving_configs(request=sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) for i in results) +def test_get_serving_config_rest_bad_request( + request_type=serving_config_service.GetServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + request = request_type(**request_init) - pages = list(client.list_serving_configs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_serving_config(request) @pytest.mark.parametrize( "request_type", [ - serving_config_service.AddControlRequest, + serving_config_service.GetServingConfigRequest, dict, ], ) -def test_add_control_rest(request_type): +def test_get_serving_config_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } 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 = gcr_serving_config.ServingConfig( + return_value = serving_config.ServingConfig( name="name_value", display_name="display_name_value", model_id="model_id_value", @@ -6603,25 +6883,25 @@ def test_add_control_rest(request_type): replacement_control_ids=["replacement_control_ids_value"], ignore_control_ids=["ignore_control_ids_value"], diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, enable_category_filter_level="enable_category_filter_level_value", ignore_recs_denylist=True, solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.add_control(request) + response = client.get_serving_config(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) + assert isinstance(response, serving_config.ServingConfig) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.model_id == "model_id_value" @@ -6640,147 +6920,138 @@ def test_add_control_rest(request_type): assert response.diversity_level == "diversity_level_value" assert ( response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) assert response.enable_category_filter_level == "enable_category_filter_level_value" assert response.ignore_recs_denylist is True assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.add_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_get_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.GetServingConfigRequest.pb( + serving_config_service.GetServingConfigRequest() ) - client._transport._wrapped_methods[client._transport.add_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.add_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = serving_config.ServingConfig.to_json( + serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.GetServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = serving_config.ServingConfig() - client.add_control(request) + client.get_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_add_control_rest_required_fields( - request_type=serving_config_service.AddControlRequest, +def test_list_serving_configs_rest_bad_request( + request_type=serving_config_service.ListServingConfigsRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_serving_configs(request) - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.ListServingConfigsRequest, + dict, + ], +) +def test_list_serving_configs_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() # 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 - - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.add_control(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = serving_config_service.ListServingConfigsResponse( + next_page_token="next_page_token_value", + ) -def test_add_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.add_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) + # Convert return value to protobuf type + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value ) - ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_serving_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_control_rest_interceptors(null_interceptor): +def test_list_serving_configs_rest_interceptors(null_interceptor): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6788,19 +7059,20 @@ def test_add_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_add_control" + transports.ServingConfigServiceRestInterceptor, "post_list_serving_configs" ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_add_control" + transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = serving_config_service.AddControlRequest.pb( - serving_config_service.AddControlRequest() + pb_message = serving_config_service.ListServingConfigsRequest.pb( + serving_config_service.ListServingConfigsRequest() ) transcode.return_value = { "method": "post", @@ -6809,22 +7081,22 @@ def test_add_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse.to_json( + serving_config_service.ListServingConfigsResponse() ) + req.return_value.content = return_value - request = serving_config_service.AddControlRequest() + request = serving_config_service.ListServingConfigsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + post.return_value = serving_config_service.ListServingConfigsResponse() - client.add_control( + client.list_serving_configs( request, metadata=[ ("key", "val"), @@ -6837,13 +7109,11 @@ def test_add_control_rest_interceptors(null_interceptor): def test_add_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.AddControlRequest + request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" @@ -6855,89 +7125,25 @@ def test_add_control_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.add_control(request) -def test_add_control_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.add_control(**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/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" - % client.transport._host, - args[1], - ) - - -def test_add_control_rest_flattened_error(transport: str = "rest"): - client = ServingConfigServiceClient( - 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.add_control( - serving_config_service.AddControlRequest(), - serving_config="serving_config_value", - ) - - -def test_add_control_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - serving_config_service.RemoveControlRequest, + serving_config_service.AddControlRequest, dict, ], ) -def test_remove_control_rest(request_type): +def test_add_control_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -6971,15 +7177,15 @@ def test_remove_control_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_control(request) + response = client.add_control(request) # Establish that the response is the type that we expect. assert isinstance(response, gcr_serving_config.ServingConfig) @@ -7008,136 +7214,168 @@ def test_remove_control_rest(request_type): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.remove_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_control_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_add_control" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_add_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.AddControlRequest.pb( + serving_config_service.AddControlRequest() ) - client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.remove_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.AddControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) + client.add_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_remove_control_rest_required_fields( +def test_remove_control_rest_bad_request( request_type=serving_config_service.RemoveControlRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - # 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 - - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_control(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_control(request) +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.RemoveControlRequest, + dict, + ], +) +def test_remove_control_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) -def test_remove_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.remove_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) - ) + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7149,6 +7387,7 @@ def test_remove_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -7170,12 +7409,12 @@ def test_remove_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( + return_value = gcr_serving_config.ServingConfig.to_json( gcr_serving_config.ServingConfig() ) + req.return_value.content = return_value request = serving_config_service.RemoveControlRequest() metadata = [ @@ -7197,19 +7436,17 @@ def test_remove_control_rest_interceptors(null_interceptor): post.assert_called_once() -def test_remove_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.RemoveControlRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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( @@ -7217,181 +7454,263 @@ def test_remove_control_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.remove_control(request) + client.get_operation(request) -def test_remove_control_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/operations/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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.remove_control(**mock_args) + response = client.get_operation(request) - # 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/v2/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_remove_control_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config="serving_config_value", - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -def test_remove_control_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert client is not None - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + client.update_serving_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + client.get_serving_config(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + client.add_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -8028,136 +8347,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8185,7 +8374,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8240,7 +8429,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8287,7 +8476,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8330,7 +8519,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8385,7 +8574,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8432,7 +8621,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8448,22 +8637,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_user_event_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_user_event_service.py index 38ee2d19f24a..0b6a1dce820f 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_user_event_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2/test_user_event_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import httpbody_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -49,17 +66,9 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2.services.user_event_service import ( UserEventServiceAsyncClient, @@ -77,10 +86,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1236,25 +1259,6 @@ def test_write_user_event(request_type, transport: str = "grpc"): assert response.entity == "entity_value" -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - def test_write_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1320,43 +1324,6 @@ def test_write_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_write_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - user_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - ) - response = await client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - @pytest.mark.asyncio async def test_write_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1365,7 +1332,7 @@ async def test_write_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1405,7 +1372,7 @@ async def test_write_user_event_async( request_type=user_event_service.WriteUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1499,7 +1466,7 @@ def test_write_user_event_field_headers(): @pytest.mark.asyncio async def test_write_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1568,27 +1535,6 @@ def test_collect_user_event(request_type, transport: str = "grpc"): assert response.data == b"data_blob" -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - def test_collect_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1666,32 +1612,6 @@ def test_collect_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_collect_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - ) - response = await client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - @pytest.mark.asyncio async def test_collect_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1700,7 +1620,7 @@ async def test_collect_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1740,7 +1660,7 @@ async def test_collect_user_event_async( request_type=user_event_service.CollectUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1812,7 +1732,7 @@ def test_collect_user_event_field_headers(): @pytest.mark.asyncio async def test_collect_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1878,27 +1798,6 @@ def test_purge_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - def test_purge_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1973,29 +1872,6 @@ def test_purge_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - @pytest.mark.asyncio async def test_purge_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2004,7 +1880,7 @@ async def test_purge_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2048,7 +1924,7 @@ async def test_purge_user_events_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2115,7 +1991,7 @@ def test_purge_user_events_field_headers(): @pytest.mark.asyncio async def test_purge_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2181,27 +2057,6 @@ def test_import_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - def test_import_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2276,29 +2131,6 @@ def test_import_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - @pytest.mark.asyncio async def test_import_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2307,7 +2139,7 @@ async def test_import_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2351,7 +2183,7 @@ async def test_import_user_events_async( transport: str = "grpc_asyncio", request_type=import_config.ImportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2418,7 +2250,7 @@ def test_import_user_events_field_headers(): @pytest.mark.asyncio async def test_import_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2484,27 +2316,6 @@ def test_rejoin_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - def test_rejoin_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2579,29 +2390,6 @@ def test_rejoin_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_rejoin_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - @pytest.mark.asyncio async def test_rejoin_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2610,7 +2398,7 @@ async def test_rejoin_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2655,7 +2443,7 @@ async def test_rejoin_user_events_async( request_type=user_event_service.RejoinUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2722,7 +2510,7 @@ def test_rejoin_user_events_field_headers(): @pytest.mark.asyncio async def test_rejoin_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2753,274 +2541,14 @@ async def test_rejoin_user_events_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.WriteUserEventRequest, - dict, - ], -) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["user_event"] = { - "event_type": "event_type_value", - "visitor_id": "visitor_id_value", - "session_id": "session_id_value", - "event_time": {"seconds": 751, "nanos": 543}, - "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], - "attribution_token": "attribution_token_value", - "product_details": [ - { - "product": { - "expire_time": {}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": [ - "color_families_value1", - "color_families_value2", - ], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - }, - "quantity": {}, - } - ], - "completion_detail": { - "completion_attribution_token": "completion_attribution_token_value", - "selected_suggestion": "selected_suggestion_value", - "selected_position": 1821, - }, - "attributes": {}, - "cart_id": "cart_id_value", - "purchase_transaction": { - "id": "id_value", - "revenue": 0.762, - "tax": 0.333, - "cost": 0.441, - "currency_code": "currency_code_value", - }, - "search_query": "search_query_value", - "filter": "filter_value", - "order_by": "order_by_value", - "offset": 647, - "page_categories": ["page_categories_value1", "page_categories_value2"], - "user_info": { - "user_id": "user_id_value", - "ip_address": "ip_address_value", - "user_agent": "user_agent_value", - "direct_user_request": True, - }, - "uri": "uri_value", - "referrer_uri": "referrer_uri_value", - "page_view_id": "page_view_id_value", - "entity": "entity_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["user_event"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["user_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][field][subfield] - 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_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == "event_type_value" - assert response.visitor_id == "visitor_id_value" - assert response.session_id == "session_id_value" - assert response.experiment_ids == ["experiment_ids_value"] - assert response.attribution_token == "attribution_token_value" - assert response.cart_id == "cart_id_value" - assert response.search_query == "search_query_value" - assert response.filter == "filter_value" - assert response.order_by == "order_by_value" - assert response.offset == 647 - assert response.page_categories == ["page_categories_value"] - assert response.uri == "uri_value" - assert response.referrer_uri == "referrer_uri_value" - assert response.page_view_id == "page_view_id_value" - assert response.entity == "entity_value" - - -def test_write_user_event_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_write_user_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3145,131 +2673,6 @@ def test_write_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_write_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb( - user_event_service.WriteUserEventRequest() - ) - 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_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.WriteUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.CollectUserEventRequest, - dict, - ], -) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == "content_type_value" - assert response.data == b"data_blob" - - def test_collect_user_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3430,126 +2833,6 @@ def test_collect_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_collect_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb( - user_event_service.CollectUserEventRequest() - ) - 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.CollectUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeUserEventsRequest, - dict, - ], -) -def test_purge_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_purge_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3685,137 +2968,13 @@ def test_purge_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_purge_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_purge_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeUserEventsRequest.pb( - purge_config.PurgeUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = purge_config.PurgeUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_user_events_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.purge_user_events(request) - - -def test_purge_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportUserEventsRequest, - dict, - ], -) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_import_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -3942,130 +3101,6 @@ def test_import_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_import_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_import_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb( - import_config.ImportUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = import_config.ImportUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.RejoinUserEventsRequest, - dict, - ], -) -def test_rejoin_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.rejoin_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_rejoin_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4191,54 +3226,1074 @@ def test_rejoin_user_events_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rejoin_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.RejoinUserEventsRequest.pb( - user_event_service.RejoinUserEventsRequest() + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - request = user_event_service.RejoinUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = UserEventServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserEventServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_write_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + ) + await client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_collect_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + ) + await client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_rejoin_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserEventServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_write_user_event_rest_bad_request( + request_type=user_event_service.WriteUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.write_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.WriteUserEventRequest, + dict, + ], +) +def test_write_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["user_event"] = { + "event_type": "event_type_value", + "visitor_id": "visitor_id_value", + "session_id": "session_id_value", + "event_time": {"seconds": 751, "nanos": 543}, + "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], + "attribution_token": "attribution_token_value", + "product_details": [ + { + "product": { + "expire_time": {}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": [ + "color_families_value1", + "color_families_value2", + ], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + }, + "quantity": {}, + } + ], + "completion_detail": { + "completion_attribution_token": "completion_attribution_token_value", + "selected_suggestion": "selected_suggestion_value", + "selected_position": 1821, + }, + "attributes": {}, + "cart_id": "cart_id_value", + "purchase_transaction": { + "id": "id_value", + "revenue": 0.762, + "tax": 0.333, + "cost": 0.441, + "currency_code": "currency_code_value", + }, + "search_query": "search_query_value", + "filter": "filter_value", + "order_by": "order_by_value", + "offset": 647, + "page_categories": ["page_categories_value1", "page_categories_value2"], + "user_info": { + "user_id": "user_id_value", + "ip_address": "ip_address_value", + "user_agent": "user_agent_value", + "direct_user_request": True, + }, + "uri": "uri_value", + "referrer_uri": "referrer_uri_value", + "page_view_id": "page_view_id_value", + "entity": "entity_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][field][subfield] + 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_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == "event_type_value" + assert response.visitor_id == "visitor_id_value" + assert response.session_id == "session_id_value" + assert response.experiment_ids == ["experiment_ids_value"] + assert response.attribution_token == "attribution_token_value" + assert response.cart_id == "cart_id_value" + assert response.search_query == "search_query_value" + assert response.filter == "filter_value" + assert response.order_by == "order_by_value" + assert response.offset == 647 + assert response.page_categories == ["page_categories_value"] + assert response.uri == "uri_value" + assert response.referrer_uri == "referrer_uri_value" + assert response.page_view_id == "page_view_id_value" + assert response.entity == "entity_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_write_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb( + user_event_service.WriteUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = user_event.UserEvent.to_json(user_event.UserEvent()) + req.return_value.content = return_value + + request = user_event_service.WriteUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request( + request_type=user_event_service.CollectUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.collect_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.CollectUserEventRequest, + dict, + ], +) +def test_collect_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == "content_type_value" + assert response.data == b"data_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_collect_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb( + user_event_service.CollectUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(httpbody_pb2.HttpBody()) + req.return_value.content = return_value + + request = user_event_service.CollectUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request( + request_type=purge_config.PurgeUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeUserEventsRequest, + dict, + ], +) +def test_purge_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_purge_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_purge_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeUserEventsRequest.pb( + purge_config.PurgeUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = purge_config.PurgeUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request( + request_type=import_config.ImportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportUserEventsRequest, + dict, + ], +) +def test_import_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_import_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_import_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb( + import_config.ImportUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = import_config.ImportUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.rejoin_user_events( + client.import_user_events( request, metadata=[ ("key", "val"), @@ -4251,13 +4306,11 @@ def test_rejoin_user_events_rest_interceptors(null_interceptor): def test_rejoin_user_events_rest_bad_request( - transport: str = "rest", request_type=user_event_service.RejoinUserEventsRequest + request_type=user_event_service.RejoinUserEventsRequest, ): client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) @@ -4267,123 +4320,356 @@ def test_rejoin_user_events_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.rejoin_user_events(request) -def test_rejoin_user_events_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.RejoinUserEventsRequest, + dict, + ], +) +def test_rejoin_user_events_rest_call_success(request_type): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.rejoin_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rejoin_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.RejoinUserEventsRequest.pb( + user_event_service.RejoinUserEventsRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = user_event_service.RejoinUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.rejoin_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + client.collect_user_event(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + client.purge_user_events(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.UserEventServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + client.rejoin_user_events(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -4626,23 +4912,6 @@ def test_user_event_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -5069,136 +5338,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5226,7 +5365,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5281,7 +5420,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5328,7 +5467,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5371,7 +5510,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5426,7 +5565,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5473,7 +5612,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -5489,22 +5628,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_analytics_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_analytics_service.py index 58de4da2a153..6c355aaae2d4 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_analytics_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_analytics_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,14 +62,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2alpha.services.analytics_service import ( AnalyticsServiceAsyncClient, @@ -62,10 +71,24 @@ from google.cloud.retail_v2alpha.types import export_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1192,27 +1215,6 @@ def test_export_analytics_metrics(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_analytics_metrics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - def test_export_analytics_metrics_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,29 +1292,6 @@ def test_export_analytics_metrics_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_analytics_metrics_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - @pytest.mark.asyncio async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1321,7 +1300,7 @@ async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1345,7 @@ async def test_export_analytics_metrics_async( request_type=export_config.ExportAnalyticsMetricsRequest, ): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_export_analytics_metrics_field_headers(): @pytest.mark.asyncio async def test_export_analytics_metrics_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1464,41 +1443,6 @@ async def test_export_analytics_metrics_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportAnalyticsMetricsRequest, - dict, - ], -) -def test_export_analytics_metrics_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_analytics_metrics(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_analytics_metrics_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1633,95 +1577,6 @@ def test_export_analytics_metrics_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_analytics_metrics_rest_interceptors(null_interceptor): - transport = transports.AnalyticsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AnalyticsServiceRestInterceptor(), - ) - client = AnalyticsServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" - ) as post, mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportAnalyticsMetricsRequest.pb( - export_config.ExportAnalyticsMetricsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportAnalyticsMetricsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_analytics_metrics( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_analytics_metrics_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportAnalyticsMetricsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.export_analytics_metrics(request) - - -def test_export_analytics_metrics_rest_error(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnalyticsServiceGrpcTransport( @@ -1814,87 +1669,444 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = AnalyticsServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = AnalyticsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.AnalyticsServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_analytics_metrics(request=None) -def test_analytics_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + assert args[0] == request_msg -def test_analytics_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2alpha.services.analytics_service.transports.AnalyticsServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "export_analytics_metrics", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = AnalyticsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - with pytest.raises(NotImplementedError): - transport.close() - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client +def test_initialize_client_w_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_analytics_metrics_empty_call_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_analytics_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.retail_v2alpha.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AnalyticsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_export_analytics_metrics_rest_bad_request( + request_type=export_config.ExportAnalyticsMetricsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_analytics_metrics(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportAnalyticsMetricsRequest, + dict, + ], +) +def test_export_analytics_metrics_rest_call_success(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_analytics_metrics(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_analytics_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsServiceRestInterceptor(), + ) + client = AnalyticsServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" + ) as post, mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportAnalyticsMetricsRequest.pb( + export_config.ExportAnalyticsMetricsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportAnalyticsMetricsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_analytics_metrics( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_analytics_service_rest_lro_client(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnalyticsServiceGrpcTransport, + ) + + +def test_analytics_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_analytics_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2alpha.services.analytics_service.transports.AnalyticsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "export_analytics_metrics", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_analytics_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.retail_v2alpha.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnalyticsServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", @@ -2064,23 +2276,6 @@ def test_analytics_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_analytics_service_rest_lro_client(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -2435,141 +2630,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = AnalyticsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2597,7 +2657,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2652,7 +2712,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2699,7 +2759,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2742,7 +2802,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2797,7 +2857,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2844,7 +2904,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2860,22 +2920,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_branch_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_branch_service.py index 3ffce6e5f89a..c2bb679e94a2 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_branch_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_branch_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,15 +53,7 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2alpha.services.branch_service import ( BranchServiceAsyncClient, @@ -54,10 +63,24 @@ from google.cloud.retail_v2alpha.types import branch, branch_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1148,25 +1171,6 @@ def test_list_branches(request_type, transport: str = "grpc"): assert isinstance(response, branch_service.ListBranchesResponse) -def test_list_branches_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_branches), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_branches() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == branch_service.ListBranchesRequest() - - def test_list_branches_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1230,27 +1234,6 @@ def test_list_branches_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_branches_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_branches), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - branch_service.ListBranchesResponse() - ) - response = await client.list_branches() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == branch_service.ListBranchesRequest() - - @pytest.mark.asyncio async def test_list_branches_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1259,7 +1242,7 @@ async def test_list_branches_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1298,7 +1281,7 @@ async def test_list_branches_async( transport: str = "grpc_asyncio", request_type=branch_service.ListBranchesRequest ): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1361,7 +1344,7 @@ def test_list_branches_field_headers(): @pytest.mark.asyncio async def test_list_branches_field_headers_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1431,7 +1414,7 @@ def test_list_branches_flattened_error(): @pytest.mark.asyncio async def test_list_branches_flattened_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1460,7 +1443,7 @@ async def test_list_branches_flattened_async(): @pytest.mark.asyncio async def test_list_branches_flattened_error_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1512,25 +1495,6 @@ def test_get_branch(request_type, transport: str = "grpc"): assert response.is_default is True -def test_get_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_branch), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == branch_service.GetBranchRequest() - - def test_get_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1594,38 +1558,13 @@ def test_get_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_branch), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - branch.Branch( - name="name_value", - display_name="display_name_value", - is_default=True, - ) - ) - response = await client.get_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == branch_service.GetBranchRequest() - - @pytest.mark.asyncio async def test_get_branch_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1664,7 +1603,7 @@ async def test_get_branch_async( transport: str = "grpc_asyncio", request_type=branch_service.GetBranchRequest ): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1734,7 +1673,7 @@ def test_get_branch_field_headers(): @pytest.mark.asyncio async def test_get_branch_field_headers_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1802,7 +1741,7 @@ def test_get_branch_flattened_error(): @pytest.mark.asyncio async def test_get_branch_flattened_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1829,7 +1768,7 @@ async def test_get_branch_flattened_async(): @pytest.mark.asyncio async def test_get_branch_flattened_error_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1841,43 +1780,6 @@ async def test_get_branch_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - branch_service.ListBranchesRequest, - dict, - ], -) -def test_list_branches_rest(request_type): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = branch_service.ListBranchesResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = branch_service.ListBranchesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_branches(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, branch_service.ListBranchesResponse) - - def test_list_branches_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1999,87 +1901,6 @@ def test_list_branches_rest_unset_required_fields(): assert set(unset_fields) == (set(("view",)) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_branches_rest_interceptors(null_interceptor): - transport = transports.BranchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.BranchServiceRestInterceptor(), - ) - client = BranchServiceClient(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.BranchServiceRestInterceptor, "post_list_branches" - ) as post, mock.patch.object( - transports.BranchServiceRestInterceptor, "pre_list_branches" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = branch_service.ListBranchesRequest.pb( - branch_service.ListBranchesRequest() - ) - 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 = branch_service.ListBranchesResponse.to_json( - branch_service.ListBranchesResponse() - ) - - request = branch_service.ListBranchesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = branch_service.ListBranchesResponse() - - client.list_branches( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_branches_rest_bad_request( - transport: str = "rest", request_type=branch_service.ListBranchesRequest -): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_branches(request) - - def test_list_branches_rest_flattened(): client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2139,78 +1960,26 @@ def test_list_branches_rest_flattened_error(transport: str = "rest"): ) -def test_list_branches_rest_error(): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_get_branch_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - branch_service.GetBranchRequest, - dict, - ], -) -def test_get_branch_rest(request_type): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - request = request_type(**request_init) + # Ensure method has been cached + assert client._transport.get_branch in client._transport._wrapped_methods - # 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 = branch.Branch( - name="name_value", - display_name="display_name_value", - is_default=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = branch.Branch.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_branch(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, branch.Branch) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.is_default is True - - -def test_get_branch_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_branch in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[client._transport.get_branch] = mock_rpc @@ -2310,87 +2079,6 @@ def test_get_branch_rest_unset_required_fields(): assert set(unset_fields) == (set(("view",)) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_branch_rest_interceptors(null_interceptor): - transport = transports.BranchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.BranchServiceRestInterceptor(), - ) - client = BranchServiceClient(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.BranchServiceRestInterceptor, "post_get_branch" - ) as post, mock.patch.object( - transports.BranchServiceRestInterceptor, "pre_get_branch" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = branch_service.GetBranchRequest.pb( - branch_service.GetBranchRequest() - ) - 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 = branch.Branch.to_json(branch.Branch()) - - request = branch_service.GetBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = branch.Branch() - - client.get_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_branch_rest_bad_request( - transport: str = "rest", request_type=branch_service.GetBranchRequest -): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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_branch(request) - - def test_get_branch_rest_flattened(): client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2450,12 +2138,6 @@ def test_get_branch_rest_flattened_error(transport: str = "rest"): ) -def test_get_branch_rest_error(): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.BranchServiceGrpcTransport( @@ -2497,69 +2179,601 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.BranchServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.BranchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BranchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BranchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BranchServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BranchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BranchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BranchServiceGrpcTransport, + transports.BranchServiceGrpcAsyncIOTransport, + transports.BranchServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = BranchServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_branches_empty_call_grpc(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_branches), "__call__") as call: + call.return_value = branch_service.ListBranchesResponse() + client.list_branches(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.ListBranchesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_branch_empty_call_grpc(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_branch), "__call__") as call: + call.return_value = branch.Branch() + client.get_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.GetBranchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BranchServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BranchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_branches_empty_call_grpc_asyncio(): + client = BranchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_branches), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + branch_service.ListBranchesResponse() + ) + await client.list_branches(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.ListBranchesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_branch_empty_call_grpc_asyncio(): + client = BranchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_branch), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + branch.Branch( + name="name_value", + display_name="display_name_value", + is_default=True, + ) + ) + await client.get_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.GetBranchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BranchServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_branches_rest_bad_request( + request_type=branch_service.ListBranchesRequest, +): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_branches(request) + + +@pytest.mark.parametrize( + "request_type", + [ + branch_service.ListBranchesRequest, + dict, + ], +) +def test_list_branches_rest_call_success(request_type): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = branch_service.ListBranchesResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = branch_service.ListBranchesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_branches(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, branch_service.ListBranchesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_branches_rest_interceptors(null_interceptor): + transport = transports.BranchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BranchServiceRestInterceptor(), + ) + client = BranchServiceClient(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.BranchServiceRestInterceptor, "post_list_branches" + ) as post, mock.patch.object( + transports.BranchServiceRestInterceptor, "pre_list_branches" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = branch_service.ListBranchesRequest.pb( + branch_service.ListBranchesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = branch_service.ListBranchesResponse.to_json( + branch_service.ListBranchesResponse() + ) + req.return_value.content = return_value + + request = branch_service.ListBranchesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = branch_service.ListBranchesResponse() + + client.list_branches( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_branch_rest_bad_request(request_type=branch_service.GetBranchRequest): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + branch_service.GetBranchRequest, + dict, + ], +) +def test_get_branch_rest_call_success(request_type): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = branch.Branch( + name="name_value", + display_name="display_name_value", + is_default=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = branch.Branch.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_branch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, branch.Branch) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_default is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_branch_rest_interceptors(null_interceptor): + transport = transports.BranchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BranchServiceRestInterceptor(), + ) + client = BranchServiceClient(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.BranchServiceRestInterceptor, "post_get_branch" + ) as post, mock.patch.object( + transports.BranchServiceRestInterceptor, "pre_get_branch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = branch_service.GetBranchRequest.pb( + branch_service.GetBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = branch.Branch.to_json(branch.Branch()) + req.return_value.content = return_value + + request = branch_service.GetBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = branch.Branch() + + client.get_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = BranchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BranchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BranchServiceClient(transport=transport) - assert client.transport is transport + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BranchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - channel = transport.grpc_channel - assert channel + assert client is not None - transport = transports.BranchServiceGrpcAsyncIOTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_branches_empty_call_rest(): + client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_branches), "__call__") as call: + client.list_branches(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BranchServiceGrpcTransport, - transports.BranchServiceGrpcAsyncIOTransport, - transports.BranchServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.ListBranchesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = BranchServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_branch_empty_call_rest(): + client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_branch), "__call__") as call: + client.get_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = branch_service.GetBranchRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -3204,141 +3418,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = BranchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3366,7 +3445,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3421,7 +3500,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3468,7 +3547,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3511,7 +3590,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3566,7 +3645,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3613,7 +3692,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = BranchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3629,22 +3708,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = BranchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = BranchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = BranchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_catalog_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_catalog_service.py index 19fa6f73117f..e1100b5016e6 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_catalog_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_catalog_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,16 +54,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import date_pb2 # type: ignore -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.retail_v2alpha.services.catalog_service import ( CatalogServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2alpha.types import catalog as gcr_catalog +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1160,25 +1183,6 @@ def test_list_catalogs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - def test_list_catalogs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1244,29 +1248,6 @@ def test_list_catalogs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_catalogs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - @pytest.mark.asyncio async def test_list_catalogs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1275,7 +1256,7 @@ async def test_list_catalogs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1314,7 +1295,7 @@ async def test_list_catalogs_async( transport: str = "grpc_asyncio", request_type=catalog_service.ListCatalogsRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1380,7 +1361,7 @@ def test_list_catalogs_field_headers(): @pytest.mark.asyncio async def test_list_catalogs_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1450,7 +1431,7 @@ def test_list_catalogs_flattened_error(): @pytest.mark.asyncio async def test_list_catalogs_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1479,7 +1460,7 @@ async def test_list_catalogs_flattened_async(): @pytest.mark.asyncio async def test_list_catalogs_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1589,7 +1570,7 @@ def test_list_catalogs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_catalogs_async_pager(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1639,7 +1620,7 @@ async def test_list_catalogs_async_pager(): @pytest.mark.asyncio async def test_list_catalogs_async_pages(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1723,25 +1704,6 @@ def test_update_catalog(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - def test_update_catalog_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1801,30 +1763,6 @@ def test_update_catalog_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_catalog_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - @pytest.mark.asyncio async def test_update_catalog_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1833,7 +1771,7 @@ async def test_update_catalog_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1872,7 +1810,7 @@ async def test_update_catalog_async( transport: str = "grpc_asyncio", request_type=catalog_service.UpdateCatalogRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1940,7 +1878,7 @@ def test_update_catalog_field_headers(): @pytest.mark.asyncio async def test_update_catalog_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2013,7 +1951,7 @@ def test_update_catalog_flattened_error(): @pytest.mark.asyncio async def test_update_catalog_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1982,7 @@ async def test_update_catalog_flattened_async(): @pytest.mark.asyncio async def test_update_catalog_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2092,27 +2030,6 @@ def test_set_default_branch(request_type, transport: str = "grpc"): assert response is None -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - def test_set_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2186,27 +2103,6 @@ def test_set_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_set_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2215,7 +2111,7 @@ async def test_set_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2255,7 +2151,7 @@ async def test_set_default_branch_async( request_type=catalog_service.SetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2320,7 +2216,7 @@ def test_set_default_branch_field_headers(): @pytest.mark.asyncio async def test_set_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2392,7 +2288,7 @@ def test_set_default_branch_flattened_error(): @pytest.mark.asyncio async def test_set_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2421,7 +2317,7 @@ async def test_set_default_branch_flattened_async(): @pytest.mark.asyncio async def test_set_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2473,27 +2369,6 @@ def test_get_default_branch(request_type, transport: str = "grpc"): assert response.note == "note_value" -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - def test_get_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2563,32 +2438,6 @@ def test_get_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - ) - response = await client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_get_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2597,7 +2446,7 @@ async def test_get_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2637,7 +2486,7 @@ async def test_get_default_branch_async( request_type=catalog_service.GetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2709,7 +2558,7 @@ def test_get_default_branch_field_headers(): @pytest.mark.asyncio async def test_get_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2783,7 +2632,7 @@ def test_get_default_branch_flattened_error(): @pytest.mark.asyncio async def test_get_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2814,7 +2663,7 @@ async def test_get_default_branch_flattened_async(): @pytest.mark.asyncio async def test_get_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2887,27 +2736,6 @@ def test_get_completion_config(request_type, transport: str = "grpc"): ) -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - def test_get_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2978,38 +2806,6 @@ def test_get_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - @pytest.mark.asyncio async def test_get_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3018,7 +2814,7 @@ async def test_get_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3058,7 +2854,7 @@ async def test_get_completion_config_async( request_type=catalog_service.GetCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3151,7 +2947,7 @@ def test_get_completion_config_field_headers(): @pytest.mark.asyncio async def test_get_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3225,7 +3021,7 @@ def test_get_completion_config_flattened_error(): @pytest.mark.asyncio async def test_get_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3256,7 +3052,7 @@ async def test_get_completion_config_flattened_async(): @pytest.mark.asyncio async def test_get_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3329,27 +3125,6 @@ def test_update_completion_config(request_type, transport: str = "grpc"): ) -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - def test_update_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3416,38 +3191,6 @@ def test_update_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - @pytest.mark.asyncio async def test_update_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3456,7 +3199,7 @@ async def test_update_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3496,7 +3239,7 @@ async def test_update_completion_config_async( request_type=catalog_service.UpdateCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3589,7 +3332,7 @@ def test_update_completion_config_field_headers(): @pytest.mark.asyncio async def test_update_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3668,7 +3411,7 @@ def test_update_completion_config_flattened_error(): @pytest.mark.asyncio async def test_update_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3703,7 +3446,7 @@ async def test_update_completion_config_flattened_async(): @pytest.mark.asyncio async def test_update_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3759,27 +3502,6 @@ def test_get_attributes_config(request_type, transport: str = "grpc"): ) -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - def test_get_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3850,32 +3572,6 @@ def test_get_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - @pytest.mark.asyncio async def test_get_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3884,7 +3580,7 @@ async def test_get_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3924,7 +3620,7 @@ async def test_get_attributes_config_async( request_type=catalog_service.GetAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3999,7 +3695,7 @@ def test_get_attributes_config_field_headers(): @pytest.mark.asyncio async def test_get_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4073,7 +3769,7 @@ def test_get_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4104,7 +3800,7 @@ async def test_get_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4159,27 +3855,6 @@ def test_update_attributes_config(request_type, transport: str = "grpc"): ) -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - def test_update_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4246,32 +3921,6 @@ def test_update_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - @pytest.mark.asyncio async def test_update_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4280,7 +3929,7 @@ async def test_update_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4320,7 +3969,7 @@ async def test_update_attributes_config_async( request_type=catalog_service.UpdateAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4395,7 +4044,7 @@ def test_update_attributes_config_field_headers(): @pytest.mark.asyncio async def test_update_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4474,7 +4123,7 @@ def test_update_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4509,7 +4158,7 @@ async def test_update_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4565,27 +4214,6 @@ def test_add_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - def test_add_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4656,32 +4284,6 @@ def test_add_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4690,7 +4292,7 @@ async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4730,7 +4332,7 @@ async def test_add_catalog_attribute_async( request_type=catalog_service.AddCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4805,7 +4407,7 @@ def test_add_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_add_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4879,27 +4481,6 @@ def test_remove_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - def test_remove_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4972,32 +4553,6 @@ def test_remove_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5006,7 +4561,7 @@ async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5046,7 +4601,7 @@ async def test_remove_catalog_attribute_async( request_type=catalog_service.RemoveCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5121,7 +4676,7 @@ def test_remove_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_remove_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5192,27 +4747,6 @@ def test_batch_remove_catalog_attributes(request_type, transport: str = "grpc"): assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] -def test_batch_remove_catalog_attributes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_remove_catalog_attributes), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_remove_catalog_attributes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.BatchRemoveCatalogAttributesRequest() - - def test_batch_remove_catalog_attributes_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5283,32 +4817,6 @@ def test_batch_remove_catalog_attributes_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_batch_remove_catalog_attributes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_remove_catalog_attributes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.BatchRemoveCatalogAttributesResponse( - deleted_catalog_attributes=["deleted_catalog_attributes_value"], - reset_catalog_attributes=["reset_catalog_attributes_value"], - ) - ) - response = await client.batch_remove_catalog_attributes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.BatchRemoveCatalogAttributesRequest() - - @pytest.mark.asyncio async def test_batch_remove_catalog_attributes_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5317,7 +4825,7 @@ async def test_batch_remove_catalog_attributes_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5357,7 +4865,7 @@ async def test_batch_remove_catalog_attributes_async( request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5429,7 +4937,7 @@ def test_batch_remove_catalog_attributes_field_headers(): @pytest.mark.asyncio async def test_batch_remove_catalog_attributes_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5503,27 +5011,6 @@ def test_replace_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - def test_replace_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5594,32 +5081,6 @@ def test_replace_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_replace_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5628,7 +5089,7 @@ async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5668,7 +5129,7 @@ async def test_replace_catalog_attribute_async( request_type=catalog_service.ReplaceCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5743,7 +5204,7 @@ def test_replace_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_replace_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5774,46 +5235,6 @@ async def test_replace_catalog_attribute_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.ListCatalogsRequest, - dict, - ], -) -def test_list_catalogs_rest(request_type): - client = CatalogServiceClient( - 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 = catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.ListCatalogsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_catalogs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_catalogs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5948,87 +5369,6 @@ def test_list_catalogs_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_catalogs_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_list_catalogs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.ListCatalogsRequest.pb( - catalog_service.ListCatalogsRequest() - ) - 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 = catalog_service.ListCatalogsResponse.to_json( - catalog_service.ListCatalogsResponse() - ) - - request = catalog_service.ListCatalogsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.ListCatalogsResponse() - - client.list_catalogs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_catalogs_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ListCatalogsRequest -): - client = CatalogServiceClient( - 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.list_catalogs(request) - - def test_list_catalogs_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6149,182 +5489,46 @@ def test_list_catalogs_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCatalogRequest, - dict, - ], -) -def test_update_catalog_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} - } - request_init["catalog"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3", - "display_name": "display_name_value", - "product_level_config": { - "ingestion_product_type": "ingestion_product_type_value", - "merchant_center_product_id_field": "merchant_center_product_id_field_value", - }, - "merchant_center_linking_config": { - "links": [ - { - "merchant_center_account_id": 2730, - "branch_id": "branch_id_value", - "destinations": ["destinations_value1", "destinations_value2"], - "region_code": "region_code_value", - "language_code": "language_code_value", - "feeds": [ - { - "primary_feed_id": 1571, - "primary_feed_name": "primary_feed_name_value", - } - ], - } - ] - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] + # Ensure method has been cached + assert client._transport.update_catalog in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_catalog] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.update_catalog(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.update_catalog(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["catalog"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["catalog"][field])): - del request_init["catalog"][field][i][subfield] - else: - del request_init["catalog"][field][subfield] - 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 = gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_catalog.Catalog.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_catalog(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - - -def test_update_catalog_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_catalog in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_catalog] = mock_rpc - - request = {} - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_catalog(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_catalog_rest_required_fields( - request_type=catalog_service.UpdateCatalogRequest, -): - transport_class = transports.CatalogServiceRestTransport +def test_update_catalog_rest_required_fields( + request_type=catalog_service.UpdateCatalogRequest, +): + transport_class = transports.CatalogServiceRestTransport request_init = {} request = request_type(**request_init) @@ -6402,87 +5606,6 @@ def test_update_catalog_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_catalog_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_catalog" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCatalogRequest.pb( - catalog_service.UpdateCatalogRequest() - ) - 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 = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) - - request = catalog_service.UpdateCatalogRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_catalog.Catalog() - - client.update_catalog( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_catalog_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCatalogRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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.update_catalog(request) - - def test_update_catalog_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6544,48 +5667,104 @@ def test_update_catalog_rest_flattened_error(transport: str = "rest"): ) -def test_update_catalog_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_set_default_branch_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.SetDefaultBranchRequest, - dict, - ], -) -def test_set_default_branch_rest(request_type): + # Ensure method has been cached + assert ( + client._transport.set_default_branch in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_default_branch + ] = mock_rpc + + request = {} + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_default_branch(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None + # get arguments that satisfy an http rule for this method + sample_request = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + catalog="catalog_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_default_branch(request) - # Establish that the response is the type that we expect. - assert response is None + client.set_default_branch(**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/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch" + % client.transport._host, + args[1], + ) -def test_set_default_branch_rest_use_cached_wrapped_rpc(): +def test_set_default_branch_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog="catalog_value", + ) + + +def test_get_default_branch_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6600,7 +5779,7 @@ def test_set_default_branch_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.set_default_branch in client._transport._wrapped_methods + client._transport.get_default_branch in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6609,96 +5788,23 @@ def test_set_default_branch_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.set_default_branch + client._transport.get_default_branch ] = mock_rpc request = {} - client.set_default_branch(request) + client.get_default_branch(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_default_branch(request) + client.get_default_branch(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" - ) as pre: - pre.assert_not_called() - pb_message = catalog_service.SetDefaultBranchRequest.pb( - catalog_service.SetDefaultBranchRequest() - ) - 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() - - request = catalog_service.SetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.set_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_set_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.SetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.set_default_branch(request) - - -def test_set_default_branch_rest_flattened(): +def test_get_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6707,7 +5813,7 @@ def test_set_default_branch_rest_flattened(): # 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 = None + return_value = catalog_service.GetDefaultBranchResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -6723,24 +5829,26 @@ def test_set_default_branch_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.set_default_branch(**mock_args) + client.get_default_branch(**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/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch" + "%s/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch" % client.transport._host, args[1], ) -def test_set_default_branch_rest_flattened_error(transport: str = "rest"): +def test_get_default_branch_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6749,61 +5857,13 @@ def test_set_default_branch_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), + client.get_default_branch( + catalog_service.GetDefaultBranchRequest(), catalog="catalog_value", ) -def test_set_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetDefaultBranchRequest, - dict, - ], -) -def test_get_default_branch_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_default_branch(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == "branch_value" - assert response.note == "note_value" - - -def test_get_default_branch_rest_use_cached_wrapped_rpc(): +def test_get_completion_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6818,7 +5878,8 @@ def test_get_default_branch_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_default_branch in client._transport._wrapped_methods + client._transport.get_completion_config + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6827,200 +5888,126 @@ def test_get_default_branch_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_default_branch + client._transport.get_completion_config ] = mock_rpc request = {} - client.get_default_branch(request) + client.get_completion_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_default_branch(request) + client.get_completion_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_default_branch" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetDefaultBranchRequest.pb( - catalog_service.GetDefaultBranchRequest() - ) - 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 = catalog_service.GetDefaultBranchResponse.to_json( - catalog_service.GetDefaultBranchResponse() - ) - - request = catalog_service.GetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.GetDefaultBranchResponse() +def test_get_completion_config_rest_required_fields( + request_type=catalog_service.GetCompletionConfigRequest, +): + transport_class = transports.CatalogServiceRestTransport - client.get_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + 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, use_integers_for_enums=False) + ) - pre.assert_called_once() - post.assert_called_once() + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_completion_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_get_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # verify required fields with default values are now present - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/sample3"} - request = request_type(**request_init) + jsonified_request["name"] = "name_value" - # 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_default_branch(request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_completion_config._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" -def test_get_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = catalog.CompletionConfig() # 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 = catalog_service.GetDefaultBranchResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - catalog="catalog_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + 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 - client.get_default_branch(**mock_args) + response_value = Response() + response_value.status_code = 200 - # 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/v2alpha/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch" - % client.transport._host, - args[1], - ) + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_get_default_branch_rest_flattened_error(transport: str = "rest"): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + response = client.get_completion_config(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog="catalog_value", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -def test_get_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_get_completion_config_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_completion_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetCompletionConfigRequest, - dict, - ], -) -def test_get_completion_config_rest(request_type): + +def test_get_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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 = catalog.CompletionConfig( + return_value = catalog.CompletionConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + + # get truthy value for each flattened field + mock_args = dict( name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7028,33 +6015,38 @@ def test_get_completion_config_rest(request_type): # Convert return value to protobuf type return_value = catalog.CompletionConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_completion_config(request) - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" + client.get_completion_config(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/completionConfig}" + % client.transport._host, + args[1], + ) + + +def test_get_completion_config_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name="name_value", + ) + -def test_get_completion_config_rest_use_cached_wrapped_rpc(): +def test_update_completion_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7069,7 +6061,7 @@ def test_get_completion_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_completion_config + client._transport.update_completion_config in client._transport._wrapped_methods ) @@ -7079,29 +6071,28 @@ def test_get_completion_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_completion_config + client._transport.update_completion_config ] = mock_rpc request = {} - client.get_completion_config(request) + client.update_completion_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_completion_config(request) + client.update_completion_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_completion_config_rest_required_fields( - request_type=catalog_service.GetCompletionConfigRequest, +def test_update_completion_config_rest_required_fields( + request_type=catalog_service.UpdateCompletionConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7112,21 +6103,19 @@ def test_get_completion_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_completion_config._get_unset_required_fields(jsonified_request) + ).update_completion_config._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_completion_config._get_unset_required_fields(jsonified_request) + ).update_completion_config._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7147,9 +6136,10 @@ def test_get_completion_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -7162,106 +6152,23 @@ def test_get_completion_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_completion_config(request) + response = client.update_completion_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_completion_config_rest_unset_required_fields(): +def test_update_completion_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_completion_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetCompletionConfigRequest.pb( - catalog_service.GetCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.GetCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.get_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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_completion_config(request) + unset_fields = transport.update_completion_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("completionConfig",))) -def test_get_completion_config_rest_flattened(): +def test_update_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7274,12 +6181,15 @@ def test_get_completion_config_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + completion_config=catalog.CompletionConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -7292,20 +6202,20 @@ def test_get_completion_config_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_completion_config(**mock_args) + client.update_completion_config(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/completionConfig}" + "%s/v2alpha/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}" % client.transport._host, args[1], ) -def test_get_completion_config_rest_flattened_error(transport: str = "rest"): +def test_update_completion_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7314,177 +6224,14 @@ def test_get_completion_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_completion_config( - catalog_service.GetCompletionConfigRequest(), - name="name_value", - ) - - -def test_get_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCompletionConfigRequest, - dict, - ], -) -def test_update_completion_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - request_init["completion_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", - "matching_order": "matching_order_value", - "max_suggestions": 1632, - "min_prefix_length": 1810, - "auto_learning": True, - "suggestions_input_config": { - "big_query_source": { - "partition_date": {"year": 433, "month": 550, "day": 318}, - "project_id": "project_id_value", - "dataset_id": "dataset_id_value", - "table_id": "table_id_value", - "gcs_staging_dir": "gcs_staging_dir_value", - "data_schema": "data_schema_value", - } - }, - "last_suggestions_import_operation": "last_suggestions_import_operation_value", - "denylist_input_config": {}, - "last_denylist_import_operation": "last_denylist_import_operation_value", - "allowlist_input_config": {}, - "last_allowlist_import_operation": "last_allowlist_import_operation_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ - "completion_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["completion_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["completion_config"][field])): - del request_init["completion_config"][field][i][subfield] - else: - del request_init["completion_config"][field][subfield] - 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 = catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", + client.update_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_completion_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" - ) - -def test_update_completion_config_rest_use_cached_wrapped_rpc(): +def test_get_attributes_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7499,7 +6246,7 @@ def test_update_completion_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_completion_config + client._transport.get_attributes_config in client._transport._wrapped_methods ) @@ -7509,28 +6256,29 @@ def test_update_completion_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_completion_config + client._transport.get_attributes_config ] = mock_rpc request = {} - client.update_completion_config(request) + client.get_attributes_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_completion_config(request) + client.get_attributes_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_completion_config_rest_required_fields( - request_type=catalog_service.UpdateCompletionConfigRequest, +def test_get_attributes_config_rest_required_fields( + request_type=catalog_service.GetAttributesConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7541,19 +6289,21 @@ def test_update_completion_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_completion_config._get_unset_required_fields(jsonified_request) + ).get_attributes_config._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() - ).update_completion_config._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",)) + ).get_attributes_config._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 = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7562,7 +6312,7 @@ def test_update_completion_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = catalog.CompletionConfig() + return_value = catalog.AttributesConfig() # 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 @@ -7574,145 +6324,56 @@ def test_update_completion_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_completion_config(request) + response = client.get_attributes_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_completion_config_rest_unset_required_fields(): +def test_get_attributes_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_completion_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("completionConfig",))) + unset_fields = transport.get_attributes_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_get_attributes_config_rest_flattened(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCompletionConfigRequest.pb( - catalog_service.UpdateCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.UpdateCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.update_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - 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_completion_config(request) - - -def test_update_completion_config_rest_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = catalog.CompletionConfig() + return_value = catalog.AttributesConfig() # get arguments that satisfy an http rule for this method sample_request = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" } # get truthy value for each flattened field mock_args = dict( - completion_config=catalog.CompletionConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -7720,25 +6381,25 @@ def test_update_completion_config_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_completion_config(**mock_args) + client.get_attributes_config(**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/v2alpha/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}" + "%s/v2alpha/{name=projects/*/locations/*/catalogs/*/attributesConfig}" % client.transport._host, args[1], ) -def test_update_completion_config_rest_flattened_error(transport: str = "rest"): +def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7747,67 +6408,13 @@ def test_update_completion_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetAttributesConfigRequest, - dict, - ], -) -def test_get_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( + client.get_attributes_config( + catalog_service.GetAttributesConfigRequest(), name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - -def test_get_attributes_config_rest_use_cached_wrapped_rpc(): +def test_update_attributes_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7822,7 +6429,7 @@ def test_get_attributes_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_attributes_config + client._transport.update_attributes_config in client._transport._wrapped_methods ) @@ -7832,29 +6439,28 @@ def test_get_attributes_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_attributes_config + client._transport.update_attributes_config ] = mock_rpc request = {} - client.get_attributes_config(request) + client.update_attributes_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attributes_config(request) + client.update_attributes_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_attributes_config_rest_required_fields( - request_type=catalog_service.GetAttributesConfigRequest, +def test_update_attributes_config_rest_required_fields( + request_type=catalog_service.UpdateAttributesConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7865,21 +6471,19 @@ def test_get_attributes_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attributes_config._get_unset_required_fields(jsonified_request) + ).update_attributes_config._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_attributes_config._get_unset_required_fields(jsonified_request) + ).update_attributes_config._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7900,9 +6504,10 @@ def test_get_attributes_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -7915,106 +6520,23 @@ def test_get_attributes_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_attributes_config(request) + response = client.update_attributes_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_attributes_config_rest_unset_required_fields(): +def test_update_attributes_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_attributes_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetAttributesConfigRequest.pb( - catalog_service.GetAttributesConfigRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.GetAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.get_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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_attributes_config(request) + unset_fields = transport.update_attributes_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("attributesConfig",))) -def test_get_attributes_config_rest_flattened(): +def test_update_attributes_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8027,12 +6549,15 @@ def test_get_attributes_config_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + attributes_config=catalog.AttributesConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -8045,20 +6570,20 @@ def test_get_attributes_config_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_attributes_config(**mock_args) + client.update_attributes_config(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/attributesConfig}" + "%s/v2alpha/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}" % client.transport._host, args[1], ) -def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): +def test_update_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8067,142 +6592,14 @@ def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name="name_value", - ) - - -def test_get_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateAttributesConfigRequest, - dict, - ], -) -def test_update_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - request_init["attributes_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", - "catalog_attributes": {}, - "attribute_config_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ - "attributes_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["attributes_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["attributes_config"][field])): - del request_init["attributes_config"][field][i][subfield] - else: - del request_init["attributes_config"][field][subfield] - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + client.update_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - -def test_update_attributes_config_rest_use_cached_wrapped_rpc(): +def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8217,7 +6614,7 @@ def test_update_attributes_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_attributes_config + client._transport.add_catalog_attribute in client._transport._wrapped_methods ) @@ -8227,28 +6624,29 @@ def test_update_attributes_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_attributes_config + client._transport.add_catalog_attribute ] = mock_rpc request = {} - client.update_attributes_config(request) + client.add_catalog_attribute(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_attributes_config(request) + client.add_catalog_attribute(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_attributes_config_rest_required_fields( - request_type=catalog_service.UpdateAttributesConfigRequest, +def test_add_catalog_attribute_rest_required_fields( + request_type=catalog_service.AddCatalogAttributeRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} + request_init["attributes_config"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8259,19 +6657,21 @@ def test_update_attributes_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attributes_config._get_unset_required_fields(jsonified_request) + ).add_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["attributesConfig"] = "attributes_config_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attributes_config._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",)) + ).add_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "attributesConfig" in jsonified_request + assert jsonified_request["attributesConfig"] == "attributes_config_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8292,7 +6692,7 @@ def test_update_attributes_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -8308,224 +6708,168 @@ def test_update_attributes_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_attributes_config(request) + response = client.add_catalog_attribute(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_attributes_config_rest_unset_required_fields(): +def test_add_catalog_attribute_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_attributes_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("attributesConfig",))) + unset_fields = transport.add_catalog_attribute._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "attributesConfig", + "catalogAttribute", + ) + ) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateAttributesConfigRequest.pb( - catalog_service.UpdateAttributesConfigRequest() +def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - request = catalog_service.UpdateAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() + # Ensure method has been cached + assert ( + client._transport.remove_catalog_attribute + in client._transport._wrapped_methods + ) - client.update_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.remove_catalog_attribute + ] = mock_rpc - pre.assert_called_once() - post.assert_called_once() + request = {} + client.remove_catalog_attribute(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_update_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.remove_catalog_attribute(request) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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_attributes_config(request) +def test_remove_catalog_attribute_rest_required_fields( + request_type=catalog_service.RemoveCatalogAttributeRequest, +): + transport_class = transports.CatalogServiceRestTransport -def test_update_attributes_config_rest_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + request_init = {} + request_init["attributes_config"] = "" + request_init["key"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # 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 = catalog.AttributesConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } + # verify fields with default values are dropped - # get truthy value for each flattened field - mock_args = dict( - attributes_config=catalog.AttributesConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # verify required fields with default values are now present - client.update_attributes_config(**mock_args) + jsonified_request["attributesConfig"] = "attributes_config_value" + jsonified_request["key"] = "key_value" - # 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/v2alpha/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}" - % client.transport._host, - args[1], - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "attributesConfig" in jsonified_request + assert jsonified_request["attributesConfig"] == "attributes_config_value" + assert "key" in jsonified_request + assert jsonified_request["key"] == "key_value" -def test_update_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - + # Designate an appropriate value for the returned response. + return_value = catalog.AttributesConfig() + # 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 -def test_update_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.AddCatalogAttributeRequest, - dict, - ], -) -def test_add_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - request = request_type(**request_init) + response = client.remove_catalog_attribute(request) - # 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_catalog_attribute(request) +def test_remove_catalog_attribute_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + unset_fields = transport.remove_catalog_attribute._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "attributesConfig", + "key", + ) + ) ) -def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): +def test_batch_remove_catalog_attributes_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8540,7 +6884,7 @@ def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.add_catalog_attribute + client._transport.batch_remove_catalog_attributes in client._transport._wrapped_methods ) @@ -8550,29 +6894,30 @@ def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.add_catalog_attribute + client._transport.batch_remove_catalog_attributes ] = mock_rpc request = {} - client.add_catalog_attribute(request) + client.batch_remove_catalog_attributes(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.add_catalog_attribute(request) + client.batch_remove_catalog_attributes(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_add_catalog_attribute_rest_required_fields( - request_type=catalog_service.AddCatalogAttributeRequest, +def test_batch_remove_catalog_attributes_rest_required_fields( + request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} request_init["attributes_config"] = "" + request_init["attribute_keys"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8583,21 +6928,24 @@ def test_add_catalog_attribute_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).add_catalog_attribute._get_unset_required_fields(jsonified_request) + ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["attributesConfig"] = "attributes_config_value" + jsonified_request["attributeKeys"] = "attribute_keys_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).add_catalog_attribute._get_unset_required_fields(jsonified_request) + ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "attributesConfig" in jsonified_request assert jsonified_request["attributesConfig"] == "attributes_config_value" + assert "attributeKeys" in jsonified_request + assert jsonified_request["attributeKeys"] == "attribute_keys_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8606,7 +6954,7 @@ def test_add_catalog_attribute_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = catalog.AttributesConfig() + return_value = catalog_service.BatchRemoveCatalogAttributesResponse() # 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 @@ -8628,179 +6976,47 @@ def test_add_catalog_attribute_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.add_catalog_attribute(request) + response = client.batch_remove_catalog_attributes(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_add_catalog_attribute_rest_unset_required_fields(): +def test_batch_remove_catalog_attributes_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.add_catalog_attribute._get_unset_required_fields({}) + unset_fields = transport.batch_remove_catalog_attributes._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set(()) & set( ( "attributesConfig", - "catalogAttribute", + "attributeKeys", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_add_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.AddCatalogAttributeRequest.pb( - catalog_service.AddCatalogAttributeRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.AddCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.add_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.AddCatalogAttributeRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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.add_catalog_attribute(request) - - -def test_add_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.RemoveCatalogAttributeRequest, - dict, - ], -) -def test_remove_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_catalog_attribute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - -def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_replace_catalog_attribute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -8809,7 +7025,7 @@ def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.remove_catalog_attribute + client._transport.replace_catalog_attribute in client._transport._wrapped_methods ) @@ -8819,30 +7035,29 @@ def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.remove_catalog_attribute + client._transport.replace_catalog_attribute ] = mock_rpc request = {} - client.remove_catalog_attribute(request) + client.replace_catalog_attribute(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.remove_catalog_attribute(request) + client.replace_catalog_attribute(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_remove_catalog_attribute_rest_required_fields( - request_type=catalog_service.RemoveCatalogAttributeRequest, +def test_replace_catalog_attribute_rest_required_fields( + request_type=catalog_service.ReplaceCatalogAttributeRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} request_init["attributes_config"] = "" - request_init["key"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8853,24 +7068,21 @@ def test_remove_catalog_attribute_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["attributesConfig"] = "attributes_config_value" - jsonified_request["key"] = "key_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "attributesConfig" in jsonified_request assert jsonified_request["attributesConfig"] == "attributes_config_value" - assert "key" in jsonified_request - assert jsonified_request["key"] == "key_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8907,130 +7119,2115 @@ def test_remove_catalog_attribute_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_catalog_attribute(request) + response = client.replace_catalog_attribute(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_remove_catalog_attribute_rest_unset_required_fields(): +def test_replace_catalog_attribute_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.remove_catalog_attribute._get_unset_required_fields({}) + unset_fields = transport.replace_catalog_attribute._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "attributesConfig", - "key", + "catalogAttribute", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( - catalog_service.RemoveCatalogAttributeRequest() + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - request = catalog_service.RemoveCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.remove_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, ) - pre.assert_called_once() - post.assert_called_once() - + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) -def test_remove_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.RemoveCatalogAttributeRequest -): - client = CatalogServiceClient( + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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.remove_catalog_attribute(request) +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport -def test_remove_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CatalogServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + call.return_value = None + client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_remove_catalog_attributes_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + call.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() + client.batch_remove_catalog_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CatalogServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_catalogs_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_catalog_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + ) + await client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + ) + await client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_remove_catalog_attributes_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.BatchRemoveCatalogAttributesResponse( + deleted_catalog_attributes=["deleted_catalog_attributes_value"], + reset_catalog_attributes=["reset_catalog_attributes_value"], + ) + ) + await client.batch_remove_catalog_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_replace_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CatalogServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_catalogs_rest_bad_request( + request_type=catalog_service.ListCatalogsRequest, +): + client = CatalogServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_catalogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ListCatalogsRequest, + dict, + ], +) +def test_list_catalogs_rest_call_success(request_type): + client = CatalogServiceClient( + 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 = catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.ListCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_catalogs_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_list_catalogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ListCatalogsRequest.pb( + catalog_service.ListCatalogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.ListCatalogsResponse.to_json( + catalog_service.ListCatalogsResponse() + ) + req.return_value.content = return_value + + request = catalog_service.ListCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.ListCatalogsResponse() + + client.list_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_catalog_rest_bad_request( + request_type=catalog_service.UpdateCatalogRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCatalogRequest, + dict, + ], +) +def test_update_catalog_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + } + request_init["catalog"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3", + "display_name": "display_name_value", + "product_level_config": { + "ingestion_product_type": "ingestion_product_type_value", + "merchant_center_product_id_field": "merchant_center_product_id_field_value", + }, + "merchant_center_linking_config": { + "links": [ + { + "merchant_center_account_id": 2730, + "branch_id": "branch_id_value", + "destinations": ["destinations_value1", "destinations_value2"], + "region_code": "region_code_value", + "language_code": "language_code_value", + "feeds": [ + { + "primary_feed_id": 1571, + "primary_feed_name": "primary_feed_name_value", + } + ], + } + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["catalog"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["catalog"][field])): + del request_init["catalog"][field][i][subfield] + else: + del request_init["catalog"][field][subfield] + 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 = gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_catalog.Catalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_catalog_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_catalog" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCatalogRequest.pb( + catalog_service.UpdateCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) + req.return_value.content = return_value + + request = catalog_service.UpdateCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_catalog.Catalog() + + client.update_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_default_branch_rest_bad_request( + request_type=catalog_service.SetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.SetDefaultBranchRequest, + dict, + ], +) +def test_set_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_default_branch(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" + ) as pre: + pre.assert_not_called() + pb_message = catalog_service.SetDefaultBranchRequest.pb( + catalog_service.SetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = catalog_service.SetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.set_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_default_branch_rest_bad_request( + request_type=catalog_service.GetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetDefaultBranchRequest, + dict, + ], +) +def test_get_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_default_branch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == "branch_value" + assert response.note == "note_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_default_branch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetDefaultBranchRequest.pb( + catalog_service.GetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.GetDefaultBranchResponse.to_json( + catalog_service.GetDefaultBranchResponse() + ) + req.return_value.content = return_value + + request = catalog_service.GetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.GetDefaultBranchResponse() + + client.get_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_completion_config_rest_bad_request( + request_type=catalog_service.GetCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetCompletionConfigRequest, + dict, + ], +) +def test_get_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetCompletionConfigRequest.pb( + catalog_service.GetCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.GetCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.get_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_completion_config_rest_bad_request( + request_type=catalog_service.UpdateCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCompletionConfigRequest, + dict, + ], +) +def test_update_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + request_init["completion_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", + "matching_order": "matching_order_value", + "max_suggestions": 1632, + "min_prefix_length": 1810, + "auto_learning": True, + "suggestions_input_config": { + "big_query_source": { + "partition_date": {"year": 433, "month": 550, "day": 318}, + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "table_id": "table_id_value", + "gcs_staging_dir": "gcs_staging_dir_value", + "data_schema": "data_schema_value", + } + }, + "last_suggestions_import_operation": "last_suggestions_import_operation_value", + "denylist_input_config": {}, + "last_denylist_import_operation": "last_denylist_import_operation_value", + "allowlist_input_config": {}, + "last_allowlist_import_operation": "last_allowlist_import_operation_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ + "completion_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["completion_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["completion_config"][field])): + del request_init["completion_config"][field][i][subfield] + else: + del request_init["completion_config"][field][subfield] + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCompletionConfigRequest.pb( + catalog_service.UpdateCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.update_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attributes_config_rest_bad_request( + request_type=catalog_service.GetAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetAttributesConfigRequest, + dict, + ], +) +def test_get_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetAttributesConfigRequest.pb( + catalog_service.GetAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.GetAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.get_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attributes_config_rest_bad_request( + request_type=catalog_service.UpdateAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateAttributesConfigRequest, + dict, + ], +) +def test_update_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + request_init["attributes_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", + "catalog_attributes": {}, + "attribute_config_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ + "attributes_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["attributes_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["attributes_config"][field])): + del request_init["attributes_config"][field][i][subfield] + else: + del request_init["attributes_config"][field][subfield] + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateAttributesConfigRequest.pb( + catalog_service.UpdateAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.update_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_catalog_attribute_rest_bad_request( + request_type=catalog_service.AddCatalogAttributeRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_catalog_attribute(request) + - @pytest.mark.parametrize( "request_type", [ - catalog_service.BatchRemoveCatalogAttributesRequest, + catalog_service.AddCatalogAttributeRequest, dict, ], ) -def test_batch_remove_catalog_attributes_rest(request_type): +def test_add_catalog_attribute_rest_call_success(request_type): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9042,173 +9239,161 @@ def test_batch_remove_catalog_attributes_rest(request_type): # 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 = catalog_service.BatchRemoveCatalogAttributesResponse( - deleted_catalog_attributes=["deleted_catalog_attributes_value"], - reset_catalog_attributes=["reset_catalog_attributes_value"], + return_value = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( - return_value - ) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_remove_catalog_attributes(request) + response = client.add_catalog_attribute(request) # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.BatchRemoveCatalogAttributesResponse) - assert response.deleted_catalog_attributes == ["deleted_catalog_attributes_value"] - assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] - - -def test_batch_remove_catalog_attributes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.batch_remove_catalog_attributes - in client._transport._wrapped_methods - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_catalog_attribute_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CatalogServiceRestInterceptor, "post_add_catalog_attribute" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.AddCatalogAttributeRequest.pb( + catalog_service.AddCatalogAttributeRequest() ) - client._transport._wrapped_methods[ - client._transport.batch_remove_catalog_attributes - ] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.batch_remove_catalog_attributes(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = catalog_service.AddCatalogAttributeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() - client.batch_remove_catalog_attributes(request) + client.add_catalog_attribute( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_batch_remove_catalog_attributes_rest_required_fields( - request_type=catalog_service.BatchRemoveCatalogAttributesRequest, +def test_remove_catalog_attribute_rest_bad_request( + request_type=catalog_service.RemoveCatalogAttributeRequest, ): - transport_class = transports.CatalogServiceRestTransport - - request_init = {} - request_init["attributes_config"] = "" - request_init["attribute_keys"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["attributesConfig"] = "attributes_config_value" - jsonified_request["attributeKeys"] = "attribute_keys_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "attributesConfig" in jsonified_request - assert jsonified_request["attributesConfig"] == "attributes_config_value" - assert "attributeKeys" in jsonified_request - assert jsonified_request["attributeKeys"] == "attribute_keys_value" - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = catalog_service.BatchRemoveCatalogAttributesResponse() - # 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 - - # Convert return value to protobuf type - return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.batch_remove_catalog_attributes(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_catalog_attribute(request) -def test_batch_remove_catalog_attributes_rest_unset_required_fields(): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.RemoveCatalogAttributeRequest, + dict, + ], +) +def test_remove_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - unset_fields = transport.batch_remove_catalog_attributes._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "attributesConfig", - "attributeKeys", - ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): +def test_remove_catalog_attribute_rest_interceptors(null_interceptor): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9216,19 +9401,20 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): else transports.CatalogServiceRestInterceptor(), ) client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_batch_remove_catalog_attributes" + transports.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_batch_remove_catalog_attributes" + transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = catalog_service.BatchRemoveCatalogAttributesRequest.pb( - catalog_service.BatchRemoveCatalogAttributesRequest() + pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( + catalog_service.RemoveCatalogAttributeRequest() ) transcode.return_value = { "method": "post", @@ -9237,24 +9423,20 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - catalog_service.BatchRemoveCatalogAttributesResponse.to_json( - catalog_service.BatchRemoveCatalogAttributesResponse() - ) - ) + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value - request = catalog_service.BatchRemoveCatalogAttributesRequest() + request = catalog_service.RemoveCatalogAttributeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() + post.return_value = catalog.AttributesConfig() - client.batch_remove_catalog_attributes( + client.remove_catalog_attribute( request, metadata=[ ("key", "val"), @@ -9267,14 +9449,11 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): def test_batch_remove_catalog_attributes_rest_bad_request( - transport: str = "rest", request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" @@ -9286,30 +9465,25 @@ def test_batch_remove_catalog_attributes_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.batch_remove_catalog_attributes(request) -def test_batch_remove_catalog_attributes_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, + catalog_service.BatchRemoveCatalogAttributesRequest, dict, ], ) -def test_replace_catalog_attribute_rest(request_type): +def test_batch_remove_catalog_attributes_rest_call_success(request_type): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9321,161 +9495,157 @@ def test_replace_catalog_attribute_rest(request_type): # 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + return_value = catalog_service.BatchRemoveCatalogAttributesResponse( + deleted_catalog_attributes=["deleted_catalog_attributes_value"], + reset_catalog_attributes=["reset_catalog_attributes_value"], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.replace_catalog_attribute(request) + response = client.batch_remove_catalog_attributes(request) # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - + assert isinstance(response, catalog_service.BatchRemoveCatalogAttributesResponse) + assert response.deleted_catalog_attributes == ["deleted_catalog_attributes_value"] + assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] -def test_replace_catalog_attribute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) - # Ensure method has been cached - assert ( - client._transport.replace_catalog_attribute - in client._transport._wrapped_methods + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CatalogServiceRestInterceptor, "post_batch_remove_catalog_attributes" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_batch_remove_catalog_attributes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.BatchRemoveCatalogAttributesRequest.pb( + catalog_service.BatchRemoveCatalogAttributesRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.to_json( + catalog_service.BatchRemoveCatalogAttributesResponse() ) - client._transport._wrapped_methods[ - client._transport.replace_catalog_attribute - ] = mock_rpc - - request = {} - client.replace_catalog_attribute(request) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = catalog_service.BatchRemoveCatalogAttributesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() - client.replace_catalog_attribute(request) + client.batch_remove_catalog_attributes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_replace_catalog_attribute_rest_required_fields( +def test_replace_catalog_attribute_rest_bad_request( request_type=catalog_service.ReplaceCatalogAttributeRequest, ): - transport_class = transports.CatalogServiceRestTransport - - request_init = {} - request_init["attributes_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["attributesConfig"] = "attributes_config_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "attributesConfig" in jsonified_request - assert jsonified_request["attributesConfig"] == "attributes_config_value" - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = catalog.AttributesConfig() - # 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 - - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.replace_catalog_attribute(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.replace_catalog_attribute(request) +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, + ], +) +def test_replace_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) -def test_replace_catalog_attribute_rest_unset_required_fields(): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.replace_catalog_attribute._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "attributesConfig", - "catalogAttribute", - ) - ) + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.replace_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG ) @@ -9488,6 +9658,7 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): else transports.CatalogServiceRestInterceptor(), ) client = CatalogServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9509,12 +9680,10 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value request = catalog_service.ReplaceCatalogAttributeRequest() metadata = [ @@ -9536,19 +9705,82 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): post.assert_called_once() -def test_replace_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ReplaceCatalogAttributeRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" } request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -9556,122 +9788,313 @@ def test_replace_catalog_attribute_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.replace_catalog_attribute(request) + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_replace_catalog_attribute_rest_error(): +def test_initialize_client_w_rest(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + client.set_default_branch(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + client.update_attributes_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CatalogServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_remove_catalog_attributes_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + client.batch_remove_catalog_attributes(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -10376,141 +10799,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10538,7 +10826,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10593,7 +10881,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10640,7 +10928,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -10683,7 +10971,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10738,7 +11026,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10785,7 +11073,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -10801,22 +11089,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_completion_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_completion_service.py index 465406c68571..8d627e19d79b 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_completion_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_completion_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,15 +62,7 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.type import date_pb2 # type: ignore -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.retail_v2alpha.services.completion_service import ( CompletionServiceAsyncClient, @@ -63,10 +72,24 @@ from google.cloud.retail_v2alpha.types import completion_service, import_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1202,25 +1225,6 @@ def test_complete_query(request_type, transport: str = "grpc"): assert response.attribution_token == "attribution_token_value" -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - def test_complete_query_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1294,29 +1298,6 @@ def test_complete_query_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_complete_query_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - ) - response = await client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - @pytest.mark.asyncio async def test_complete_query_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1325,7 +1306,7 @@ async def test_complete_query_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1365,7 +1346,7 @@ async def test_complete_query_async( request_type=completion_service.CompleteQueryRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1431,7 +1412,7 @@ def test_complete_query_field_headers(): @pytest.mark.asyncio async def test_complete_query_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1495,27 +1476,6 @@ def test_import_completion_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - def test_import_completion_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1593,29 +1553,6 @@ def test_import_completion_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_completion_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - @pytest.mark.asyncio async def test_import_completion_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1624,7 +1561,7 @@ async def test_import_completion_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1669,7 +1606,7 @@ async def test_import_completion_data_async( request_type=import_config.ImportCompletionDataRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1736,7 +1673,7 @@ def test_import_completion_data_field_headers(): @pytest.mark.asyncio async def test_import_completion_data_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1767,46 +1704,6 @@ async def test_import_completion_data_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - completion_service.CompleteQueryRequest, - dict, - ], -) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == "attribution_token_value" - - def test_complete_query_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1971,128 +1868,6 @@ def test_complete_query_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" - ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, "pre_complete_query" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb( - completion_service.CompleteQueryRequest() - ) - 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 = completion_service.CompleteQueryResponse.to_json( - completion_service.CompleteQueryResponse() - ) - - request = completion_service.CompleteQueryRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request( - transport: str = "rest", request_type=completion_service.CompleteQueryRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportCompletionDataRequest, - dict, - ], -) -def test_import_completion_data_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_completion_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_completion_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2227,15 +2002,419 @@ def test_import_completion_data_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_completion_data_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CompletionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CompletionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_complete_query_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + ) + await client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_completion_data_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CompletionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_complete_query_rest_bad_request( + request_type=completion_service.CompleteQueryRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.complete_query(request) + + +@pytest.mark.parametrize( + "request_type", + [ + completion_service.CompleteQueryRequest, + dict, + ], +) +def test_complete_query_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == "attribution_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, "pre_complete_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb( + completion_service.CompleteQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = completion_service.CompleteQueryResponse.to_json( + completion_service.CompleteQueryResponse() + ) + req.return_value.content = return_value + + request = completion_service.CompleteQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_completion_data_rest_bad_request( + request_type=import_config.ImportCompletionDataRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_completion_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportCompletionDataRequest, + dict, + ], +) +def test_import_completion_data_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_completion_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_completion_data_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), ) client = CompletionServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -2259,12 +2438,10 @@ def test_import_completion_data_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = import_config.ImportCompletionDataRequest() metadata = [ @@ -2286,17 +2463,20 @@ def test_import_completion_data_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_completion_data_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportCompletionDataRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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( @@ -2304,122 +2484,174 @@ def test_import_completion_data_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.import_completion_data(request) + client.get_operation(request) -def test_import_completion_data_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +def test_initialize_client_w_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + assert client is not None -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + client.complete_query(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() - transport = transports.CompletionServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + client.import_completion_data(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( + +def test_completion_service_rest_lro_client(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -2659,23 +2891,6 @@ def test_completion_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_completion_service_rest_lro_client(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -3059,141 +3274,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3221,7 +3301,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3276,7 +3356,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3323,7 +3403,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3366,7 +3446,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3421,7 +3501,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3468,7 +3548,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3484,22 +3564,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_control_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_control_service.py index 97e2acb574dd..abccc75254cc 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_control_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_control_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,15 +54,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2alpha.services.control_service import ( ControlServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2alpha.types import control_service, search_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1174,25 +1197,6 @@ def test_create_control(request_type, transport: str = "grpc"): ] -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - def test_create_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1258,35 +1262,6 @@ def test_create_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - @pytest.mark.asyncio async def test_create_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1295,7 +1270,7 @@ async def test_create_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1334,7 +1309,7 @@ async def test_create_control_async( transport: str = "grpc_asyncio", request_type=control_service.CreateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1414,7 +1389,7 @@ def test_create_control_field_headers(): @pytest.mark.asyncio async def test_create_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1510,7 +1485,7 @@ def test_create_control_flattened_error(): @pytest.mark.asyncio async def test_create_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1557,7 +1532,7 @@ async def test_create_control_flattened_async(): @pytest.mark.asyncio async def test_create_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1610,25 +1585,6 @@ def test_delete_control(request_type, transport: str = "grpc"): assert response is None -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - def test_delete_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1692,25 +1648,6 @@ def test_delete_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - @pytest.mark.asyncio async def test_delete_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1719,7 +1656,7 @@ async def test_delete_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1758,7 +1695,7 @@ async def test_delete_control_async( transport: str = "grpc_asyncio", request_type=control_service.DeleteControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1819,7 +1756,7 @@ def test_delete_control_field_headers(): @pytest.mark.asyncio async def test_delete_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1887,7 +1824,7 @@ def test_delete_control_flattened_error(): @pytest.mark.asyncio async def test_delete_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1914,7 +1851,7 @@ async def test_delete_control_flattened_async(): @pytest.mark.asyncio async def test_delete_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1976,25 +1913,6 @@ def test_update_control(request_type, transport: str = "grpc"): ] -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - def test_update_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2054,35 +1972,6 @@ def test_update_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - @pytest.mark.asyncio async def test_update_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2091,7 +1980,7 @@ async def test_update_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2130,7 +2019,7 @@ async def test_update_control_async( transport: str = "grpc_asyncio", request_type=control_service.UpdateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2210,7 +2099,7 @@ def test_update_control_field_headers(): @pytest.mark.asyncio async def test_update_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2301,7 +2190,7 @@ def test_update_control_flattened_error(): @pytest.mark.asyncio async def test_update_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2344,7 +2233,7 @@ async def test_update_control_flattened_async(): @pytest.mark.asyncio async def test_update_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2413,25 +2302,6 @@ def test_get_control(request_type, transport: str = "grpc"): ] -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - def test_get_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2495,35 +2365,6 @@ def test_get_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - @pytest.mark.asyncio async def test_get_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2532,7 +2373,7 @@ async def test_get_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2571,7 +2412,7 @@ async def test_get_control_async( transport: str = "grpc_asyncio", request_type=control_service.GetControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2651,7 +2492,7 @@ def test_get_control_field_headers(): @pytest.mark.asyncio async def test_get_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2719,7 +2560,7 @@ def test_get_control_flattened_error(): @pytest.mark.asyncio async def test_get_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2746,7 +2587,7 @@ async def test_get_control_flattened_async(): @pytest.mark.asyncio async def test_get_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2794,25 +2635,6 @@ def test_list_controls(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - def test_list_controls_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2880,29 +2702,6 @@ def test_list_controls_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_controls_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control_service.ListControlsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - @pytest.mark.asyncio async def test_list_controls_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2911,7 +2710,7 @@ async def test_list_controls_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2950,7 +2749,7 @@ async def test_list_controls_async( transport: str = "grpc_asyncio", request_type=control_service.ListControlsRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3016,7 +2815,7 @@ def test_list_controls_field_headers(): @pytest.mark.asyncio async def test_list_controls_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3086,7 +2885,7 @@ def test_list_controls_flattened_error(): @pytest.mark.asyncio async def test_list_controls_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3115,7 +2914,7 @@ async def test_list_controls_flattened_async(): @pytest.mark.asyncio async def test_list_controls_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3225,7 +3024,7 @@ def test_list_controls_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_controls_async_pager(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3275,7 +3074,7 @@ async def test_list_controls_async_pager(): @pytest.mark.asyncio async def test_list_controls_async_pages(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3321,221 +3120,14 @@ async def test_list_controls_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - control_service.CreateControlRequest, - dict, - ], -) -def test_create_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["control"] = { - "facet_spec": { - "facet_key": { - "key": "key_value", - "intervals": [ - { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - } - ], - "restricted_values": [ - "restricted_values_value1", - "restricted_values_value2", - ], - "prefixes": ["prefixes_value1", "prefixes_value2"], - "contains": ["contains_value1", "contains_value2"], - "case_insensitive": True, - "order_by": "order_by_value", - "query": "query_value", - "return_min_max": True, - }, - "limit": 543, - "excluded_filter_keys": [ - "excluded_filter_keys_value1", - "excluded_filter_keys_value2", - ], - "enable_dynamic_position": True, - }, - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "name_value", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = control_service.CreateControlRequest.meta.fields["control"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - - -def test_create_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3672,100 +3264,21 @@ def test_create_control_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( +def test_create_control_rest_flattened(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), + transport="rest", ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_create_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.CreateControlRequest.pb( - control_service.CreateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.CreateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.create_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() + # 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 = gcr_control.Control() - -def test_create_control_rest_bad_request( - transport: str = "rest", request_type=control_service.CreateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_control(request) - - -def test_create_control_rest_flattened(): - client = ControlServiceClient( - 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 = gcr_control.Control() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -3826,49 +3339,6 @@ def test_create_control_rest_flattened_error(transport: str = "rest"): ) -def test_create_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.DeleteControlRequest, - dict, - ], -) -def test_delete_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_control(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3985,81 +3455,6 @@ def test_delete_control_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" - ) as pre: - pre.assert_not_called() - pb_message = control_service.DeleteControlRequest.pb( - control_service.DeleteControlRequest() - ) - 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() - - request = control_service.DeleteControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_control_rest_bad_request( - transport: str = "rest", request_type=control_service.DeleteControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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.delete_control(request) - - def test_delete_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4117,198 +3512,153 @@ def test_delete_control_rest_flattened_error(transport: str = "rest"): ) -def test_delete_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_control in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_control] = mock_rpc + + request = {} + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_control(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_control_rest_required_fields( + request_type=control_service.UpdateControlRequest, +): + transport_class = transports.ControlServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_control._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_control._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 -@pytest.mark.parametrize( - "request_type", - [ - control_service.UpdateControlRequest, - dict, - ], -) -def test_update_control_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - request_init["control"] = { - "facet_spec": { - "facet_key": { - "key": "key_value", - "intervals": [ - { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - } - ], - "restricted_values": [ - "restricted_values_value1", - "restricted_values_value2", - ], - "prefixes": ["prefixes_value1", "prefixes_value2"], - "contains": ["contains_value1", "contains_value2"], - "case_insensitive": True, - "order_by": "order_by_value", - "query": "query_value", - "return_min_max": True, - }, - "limit": 543, - "excluded_filter_keys": [ - "excluded_filter_keys_value1", - "excluded_filter_keys_value2", - ], - "enable_dynamic_position": True, - }, - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = gcr_control.Control() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = control_service.UpdateControlRequest.meta.fields["control"] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.update_control(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_control_rest_unset_required_fields(): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.update_control._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("control",))) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - request = request_type(**request_init) + +def test_update_control_rest_flattened(): + client = ControlServiceClient( + 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], + return_value = gcr_control.Control() + + # get arguments that satisfy an http rule for this method + sample_request = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + control=gcr_control.Control( + facet_spec=search_service.SearchRequest.FacetSpec( + facet_key=search_service.SearchRequest.FacetSpec.FacetKey( + key="key_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() @@ -4316,25 +3666,45 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gcr_control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_control(request) - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] + client.update_control(**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/v2alpha/{control.name=projects/*/locations/*/catalogs/*/controls/*}" + % client.transport._host, + args[1], + ) -def test_update_control_rest_use_cached_wrapped_rpc(): +def test_update_control_rest_flattened_error(transport: str = "rest"): + client = ControlServiceClient( + 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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control( + facet_spec=search_service.SearchRequest.FacetSpec( + facet_key=search_service.SearchRequest.FacetSpec.FacetKey( + key="key_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4348,34 +3718,35 @@ def test_update_control_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_control in client._transport._wrapped_methods + assert client._transport.get_control in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_control] = mock_rpc + client._transport._wrapped_methods[client._transport.get_control] = mock_rpc request = {} - client.update_control(request) + client.get_control(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_control(request) + client.get_control(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_control_rest_required_fields( - request_type=control_service.UpdateControlRequest, +def test_get_control_rest_required_fields( + request_type=control_service.GetControlRequest, ): transport_class = transports.ControlServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4386,19 +3757,21 @@ def test_update_control_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_control._get_unset_required_fields(jsonified_request) + ).get_control._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() - ).update_control._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",)) + ).get_control._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 = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4407,7 +3780,7 @@ def test_update_control_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_control.Control() + return_value = control.Control() # 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 @@ -4419,122 +3792,38 @@ def test_update_control_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_control(request) + response = client.get_control(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_control_rest_unset_required_fields(): +def test_get_control_rest_unset_required_fields(): transport = transports.ControlServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_control._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("control",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_update_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_update_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.UpdateControlRequest.pb( - control_service.UpdateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.UpdateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.update_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_control_rest_bad_request( - transport: str = "rest", request_type=control_service.UpdateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - 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_control(request) + unset_fields = transport.get_control._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_control_rest_flattened(): +def test_get_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4543,25 +3832,16 @@ def test_update_control_rest_flattened(): # 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 = gcr_control.Control() + return_value = control.Control() # get arguments that satisfy an http rule for this method sample_request = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" } # get truthy value for each flattened field mock_args = dict( - control=gcr_control.Control( - facet_spec=search_service.SearchRequest.FacetSpec( - facet_key=search_service.SearchRequest.FacetSpec.FacetKey( - key="key_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -4569,25 +3849,25 @@ def test_update_control_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_control(**mock_args) + client.get_control(**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/v2alpha/{control.name=projects/*/locations/*/catalogs/*/controls/*}" + "%s/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}" % client.transport._host, args[1], ) -def test_update_control_rest_flattened_error(transport: str = "rest"): +def test_get_control_rest_flattened_error(transport: str = "rest"): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4596,82 +3876,13 @@ def test_update_control_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control( - facet_spec=search_service.SearchRequest.FacetSpec( - facet_key=search_service.SearchRequest.FacetSpec.FacetKey( - key="key_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.GetControlRequest, - dict, - ], -) -def test_get_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = control.Control( + client.get_control( + control_service.GetControlRequest(), name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - -def test_get_control_rest_use_cached_wrapped_rpc(): +def test_list_controls_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4685,35 +3896,35 @@ def test_get_control_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_control in client._transport._wrapped_methods + assert client._transport.list_controls in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_control] = mock_rpc + client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc request = {} - client.get_control(request) + client.list_controls(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_control(request) + client.list_controls(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_control_rest_required_fields( - request_type=control_service.GetControlRequest, +def test_list_controls_rest_required_fields( + request_type=control_service.ListControlsRequest, ): transport_class = transports.ControlServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4724,21 +3935,29 @@ def test_get_control_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_control._get_unset_required_fields(jsonified_request) + ).list_controls._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_control._get_unset_required_fields(jsonified_request) + ).list_controls._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4747,7 +3966,7 @@ def test_get_control_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = control.Control() + return_value = control_service.ListControlsResponse() # 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 @@ -4768,50 +3987,1199 @@ def test_get_control_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = control.Control.pb(return_value) + return_value = control_service.ListControlsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_control(request) + response = client.list_controls(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_control_rest_unset_required_fields(): +def test_list_controls_rest_unset_required_fields(): transport = transports.ControlServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_control._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_controls._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( +def test_list_controls_rest_flattened(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), + transport="rest", ) - client = ControlServiceClient(transport=transport) - with mock.patch.object( + + # 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 = control_service.ListControlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = control_service.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_controls(**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/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls" + % client.transport._host, + args[1], + ) + + +def test_list_controls_rest_flattened_error(transport: str = "rest"): + client = ControlServiceClient( + 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.list_controls( + control_service.ListControlsRequest(), + parent="parent_value", + ) + + +def test_list_controls_rest_pager(transport: str = "rest"): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token="abc", + ), + control_service.ListControlsResponse( + controls=[], + next_page_token="def", + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token="ghi", + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + control_service.ListControlsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } + + pager = client.list_controls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) for i in results) + + pages = list(client.list_controls(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ControlServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + call.return_value = None + client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + call.return_value = control.Control() + client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ControlServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_controls_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ControlServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_control_rest_bad_request( + request_type=control_service.CreateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.CreateControlRequest, + dict, + ], +) +def test_create_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["control"] = { + "facet_spec": { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + "query": "query_value", + "return_min_max": True, + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + }, + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "name_value", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.CreateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_create_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.CreateControlRequest.pb( + control_service.CreateControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value + + request = control_service.CreateControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_control.Control() + + client.create_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_control_rest_bad_request( + request_type=control_service.DeleteControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.DeleteControlRequest, + dict, + ], +) +def test_delete_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_control(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" + ) as pre: + pre.assert_not_called() + pb_message = control_service.DeleteControlRequest.pb( + control_service.DeleteControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = control_service.DeleteControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_control_rest_bad_request( + request_type=control_service.UpdateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.UpdateControlRequest, + dict, + ], +) +def test_update_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + request_init["control"] = { + "facet_spec": { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + "query": "query_value", + "return_min_max": True, + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + }, + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.UpdateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_get_control" + transports.ControlServiceRestInterceptor, "post_update_control" ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_get_control" + transports.ControlServiceRestInterceptor, "pre_update_control" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = control_service.GetControlRequest.pb( - control_service.GetControlRequest() + pb_message = control_service.UpdateControlRequest.pb( + control_service.UpdateControlRequest() ) transcode.return_value = { "method": "post", @@ -4820,20 +5188,20 @@ def test_get_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = control.Control.to_json(control.Control()) + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value - request = control_service.GetControlRequest() + request = control_service.UpdateControlRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = control.Control() + post.return_value = gcr_control.Control() - client.get_control( + client.update_control( request, metadata=[ ("key", "val"), @@ -4845,14 +5213,10 @@ def test_get_control_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_control_rest_bad_request( - transport: str = "rest", request_type=control_service.GetControlRequest -): +def test_get_control_rest_bad_request(request_type=control_service.GetControlRequest): client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" @@ -4864,252 +5228,187 @@ def test_get_control_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.get_control(request) -def test_get_control_rest_flattened(): - client = ControlServiceClient( - 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 = control.Control() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - - # 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 - # Convert return value to protobuf type - return_value = control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_control(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/controls/*}" - % client.transport._host, - args[1], - ) - - -def test_get_control_rest_flattened_error(transport: str = "rest"): - client = ControlServiceClient( - 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_control( - control_service.GetControlRequest(), - name="name_value", - ) - - -def test_get_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - control_service.ListControlsRequest, + control_service.GetControlRequest, dict, ], ) -def test_list_controls_rest(request_type): +def test_get_control_rest_call_success(request_type): client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } 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 = control_service.ListControlsResponse( - next_page_token="next_page_token_value", + return_value = control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_controls(request) + response = client.get_control(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_controls_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert isinstance(response, control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.list_controls in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ControlServiceRestInterceptor, "post_get_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_get_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.GetControlRequest.pb( + control_service.GetControlRequest() ) - client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.list_controls(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = control.Control.to_json(control.Control()) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = control_service.GetControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = control.Control() - client.list_controls(request) + client.get_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_list_controls_rest_required_fields( +def test_list_controls_rest_bad_request( request_type=control_service.ListControlsRequest, ): - transport_class = transports.ControlServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_controls._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() - ).list_controls._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - ) - ) - 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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = control_service.ListControlsResponse() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_controls(request) - # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + control_service.ListControlsRequest, + dict, + ], +) +def test_list_controls_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.list_controls(request) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_list_controls_rest_unset_required_fields(): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = control_service.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_controls(request) - unset_fields = transport.list_controls._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5121,6 +5420,7 @@ def test_list_controls_rest_interceptors(null_interceptor): else transports.ControlServiceRestInterceptor(), ) client = ControlServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5142,12 +5442,12 @@ def test_list_controls_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = control_service.ListControlsResponse.to_json( + return_value = control_service.ListControlsResponse.to_json( control_service.ListControlsResponse() ) + req.return_value.content = return_value request = control_service.ListControlsRequest() metadata = [ @@ -5169,17 +5469,20 @@ def test_list_controls_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_controls_rest_bad_request( - transport: str = "rest", request_type=control_service.ListControlsRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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( @@ -5187,240 +5490,215 @@ def test_list_controls_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_controls(request) + client.get_operation(request) -def test_list_controls_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + 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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = control_service.ListControlsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.list_controls(**mock_args) + response = client.get_operation(request) - # 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/v2alpha/{parent=projects/*/locations/*/catalogs/*}/controls" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_list_controls_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_controls( - control_service.ListControlsRequest(), - parent="parent_value", - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -def test_list_controls_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token="abc", - ), - control_service.ListControlsResponse( - controls=[], - next_page_token="def", - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token="ghi", - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - control_service.ListControlsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - pager = client.list_controls(request=sample_request) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) for i in results) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - pages = list(client.list_controls(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + req.return_value = response_value + response = client.list_operations(request) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) +def test_initialize_client_w_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + client.create_control(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ControlServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + client.get_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ControlServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -6045,141 +6323,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6207,7 +6350,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6262,7 +6405,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6309,7 +6452,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6352,7 +6495,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6407,7 +6550,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6454,7 +6597,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6470,22 +6613,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_generative_question_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_generative_question_service.py index de54573bd2e3..defc25335850 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_generative_question_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_generative_question_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2alpha.services.generative_question_service import ( GenerativeQuestionServiceAsyncClient, @@ -57,10 +66,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1252,30 +1275,6 @@ def test_update_generative_questions_feature_config( assert response.minimum_products == 1743 -def test_update_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - def test_update_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1347,36 +1346,6 @@ def test_update_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1385,7 +1354,7 @@ async def test_update_generative_questions_feature_config_async_use_cached_wrapp # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1425,7 +1394,7 @@ async def test_update_generative_questions_feature_config_async( request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1503,7 +1472,7 @@ def test_update_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1590,7 +1559,7 @@ def test_update_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1629,7 +1598,7 @@ async def test_update_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1688,30 +1657,6 @@ def test_get_generative_questions_feature_config(request_type, transport: str = assert response.minimum_products == 1743 -def test_get_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - def test_get_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1784,36 +1729,6 @@ def test_get_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_get_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1822,7 +1737,7 @@ async def test_get_generative_questions_feature_config_async_use_cached_wrapped_ # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1862,7 +1777,7 @@ async def test_get_generative_questions_feature_config_async( request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1938,7 +1853,7 @@ def test_get_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2012,7 +1927,7 @@ def test_get_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2043,7 +1958,7 @@ async def test_get_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,30 +2009,6 @@ def test_list_generative_question_configs(request_type, transport: str = "grpc") ) -def test_list_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - def test_list_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2190,32 +2081,6 @@ def test_list_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - response = await client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2224,7 +2089,7 @@ async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2264,7 +2129,7 @@ async def test_list_generative_question_configs_async( request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2335,7 +2200,7 @@ def test_list_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_list_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2411,7 +2276,7 @@ def test_list_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2444,7 +2309,7 @@ async def test_list_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2506,30 +2371,6 @@ def test_update_generative_question_config(request_type, transport: str = "grpc" assert response.allowed_in_conversation is True -def test_update_generative_question_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - def test_update_generative_question_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2599,40 +2440,6 @@ def test_update_generative_question_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_question_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - ) - response = await client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_question_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2641,7 +2448,7 @@ async def test_update_generative_question_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2681,7 +2488,7 @@ async def test_update_generative_question_config_async( request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2763,7 +2570,7 @@ def test_update_generative_question_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_question_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2846,7 +2653,7 @@ def test_update_generative_question_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2883,7 +2690,7 @@ async def test_update_generative_question_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2942,30 +2749,6 @@ def test_batch_update_generative_question_configs( ) -def test_batch_update_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - def test_batch_update_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3038,32 +2821,6 @@ def test_batch_update_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_batch_update_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - response = await client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_batch_update_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3072,7 +2829,7 @@ async def test_batch_update_generative_question_configs_async_use_cached_wrapped # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3112,7 +2869,7 @@ async def test_batch_update_generative_question_configs_async( request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3186,7 +2943,7 @@ def test_batch_update_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3285,7 +3042,7 @@ def test_batch_update_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3334,7 +3091,7 @@ async def test_batch_update_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3353,136 +3110,6 @@ async def test_batch_update_generative_question_configs_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_update_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_questions_feature_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "feature_enabled": True, - "minimum_products": 1743, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ - "generative_questions_feature_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_questions_feature_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_questions_feature_config"][field]) - ): - del request_init["generative_questions_feature_config"][field][i][ - subfield - ] - else: - del request_init["generative_questions_feature_config"][field][subfield] - 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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - def test_update_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3617,98 +3244,6 @@ def test_update_generative_questions_feature_config_rest_unset_required_fields() ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.update_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_questions_feature_config(request) - - def test_update_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3780,70 +3315,18 @@ def test_update_generative_questions_feature_config_rest_flattened_error( ) -def test_update_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_get_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - -def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( @@ -3964,96 +3447,6 @@ def test_get_generative_questions_feature_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_get_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_get_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.get_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.get_generative_questions_feature_config(request) - - def test_get_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4117,57 +3510,6 @@ def test_get_generative_questions_feature_config_rest_flattened_error( ) -def test_get_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.ListGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_list_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, generative_question_service.ListGenerativeQuestionConfigsResponse - ) - - def test_list_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4298,132 +3640,42 @@ def test_list_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_list_generative_question_configs_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_list_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_list_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - generative_question_service.ListGenerativeQuestionConfigsRequest() - ) + + # 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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) - request = generative_question_service.ListGenerativeQuestionConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) ) - - client.list_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_generative_question_configs(request) - - -def test_list_generative_question_configs_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value client.list_generative_question_configs(**mock_args) @@ -4453,152 +3705,6 @@ def test_list_generative_question_configs_rest_flattened_error(transport: str = ) -def test_list_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionConfigRequest, - dict, - ], -) -def test_update_generative_question_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_question_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "facet": "facet_value", - "generated_question": "generated_question_value", - "final_question": "final_question_value", - "example_values": ["example_values_value1", "example_values_value2"], - "frequency": 0.978, - "allowed_in_conversation": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ - "generative_question_config" - ] - ) - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_question_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_question_config"][field]) - ): - del request_init["generative_question_config"][field][i][subfield] - else: - del request_init["generative_question_config"][field][subfield] - 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 = generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_question_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionConfig) - assert response.catalog == "catalog_value" - assert response.facet == "facet_value" - assert response.generated_question == "generated_question_value" - assert response.final_question == "final_question_value" - assert response.example_values == ["example_values_value"] - assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) - assert response.allowed_in_conversation is True - - def test_update_generative_question_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4725,108 +3831,16 @@ def test_update_generative_question_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_question_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_update_generative_question_config_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_question_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_question_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionConfig.to_json( - generative_question.GenerativeQuestionConfig() - ) - ) - - request = generative_question_service.UpdateGenerativeQuestionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionConfig() - - client.update_generative_question_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_question_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_question_config(request) - - -def test_update_generative_question_config_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = generative_question.GenerativeQuestionConfig() + # 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 = generative_question.GenerativeQuestionConfig() # get arguments that satisfy an http rule for this method sample_request = { @@ -4886,58 +3900,6 @@ def test_update_generative_question_config_rest_flattened_error( ) -def test_update_generative_question_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_batch_update_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.batch_update_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, - ) - - def test_batch_update_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5070,94 +4032,6 @@ def test_batch_update_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("requests",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_batch_update_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_batch_update_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - 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 = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - request = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - client.batch_update_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.batch_update_generative_question_configs(request) - - def test_batch_update_generative_question_configs_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5239,12 +4113,6 @@ def test_batch_update_generative_question_configs_rest_flattened_error( ) -def test_batch_update_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GenerativeQuestionServiceGrpcTransport( @@ -5286,69 +4154,1474 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GenerativeQuestionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GenerativeQuestionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GenerativeQuestionServiceGrpcTransport, + transports.GenerativeQuestionServiceGrpcAsyncIOTransport, + transports.GenerativeQuestionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = GenerativeQuestionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionConfig() + client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GenerativeQuestionServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + await client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_question_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + ) + await client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + await client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GenerativeQuestionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_update_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_update_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_questions_feature_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "feature_enabled": True, + "minimum_products": 1743, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ + "generative_questions_feature_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_questions_feature_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_questions_feature_config"][field]) + ): + del request_init["generative_questions_feature_config"][field][i][ + subfield + ] + else: + del request_init["generative_questions_feature_config"][field][subfield] + 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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.update_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_get_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_get_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_get_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.get_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_generative_question_configs_rest_bad_request( + request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.ListGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_list_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, generative_question_service.ListGenerativeQuestionConfigsResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_list_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_list_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + generative_question_service.ListGenerativeQuestionConfigsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + ) + req.return_value.content = return_value + + request = generative_question_service.ListGenerativeQuestionConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + client.list_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_generative_question_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_question_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionConfigRequest, + dict, + ], +) +def test_update_generative_question_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_question_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "facet": "facet_value", + "generated_question": "generated_question_value", + "final_question": "final_question_value", + "example_values": ["example_values_value1", "example_values_value2"], + "frequency": 0.978, + "allowed_in_conversation": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ + "generative_question_config" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_question_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_question_config"][field]) + ): + del request_init["generative_question_config"][field][i][subfield] + else: + del request_init["generative_question_config"][field][subfield] + 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 = generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_question_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionConfig) + assert response.catalog == "catalog_value" + assert response.facet == "facet_value" + assert response.generated_question == "generated_question_value" + assert response.final_question == "final_question_value" + assert response.example_values == ["example_values_value"] + assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) + assert response.allowed_in_conversation is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_question_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_question_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_question_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionConfig.to_json( + generative_question.GenerativeQuestionConfig() + ) + req.return_value.content = return_value + + request = generative_question_service.UpdateGenerativeQuestionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionConfig() + + client.update_generative_question_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_update_generative_question_configs_rest_bad_request( + request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.batch_update_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_batch_update_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_update_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_batch_update_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_batch_update_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + client.batch_update_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = GenerativeQuestionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() ) + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = GenerativeQuestionServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + assert args[0] == request_msg - transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + client.update_generative_question_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.GenerativeQuestionServiceGrpcTransport, - transports.GenerativeQuestionServiceGrpcAsyncIOTransport, - transports.GenerativeQuestionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = GenerativeQuestionServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -5950,141 +6223,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6112,7 +6250,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6167,7 +6305,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6214,7 +6352,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6257,7 +6395,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6312,7 +6450,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6359,7 +6497,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6375,22 +6513,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_merchant_center_account_link_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_merchant_center_account_link_service.py index 9cddf03dada5..e42453d880b6 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_merchant_center_account_link_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_merchant_center_account_link_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,14 +62,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2alpha.services.merchant_center_account_link_service import ( MerchantCenterAccountLinkServiceAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.retail_v2alpha.types import merchant_center_account_link +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1283,30 +1306,6 @@ def test_list_merchant_center_account_links(request_type, transport: str = "grpc ) -def test_list_merchant_center_account_links_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_merchant_center_account_links), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_merchant_center_account_links() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() - ) - - def test_list_merchant_center_account_links_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1381,32 +1380,6 @@ def test_list_merchant_center_account_links_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_merchant_center_account_links_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_merchant_center_account_links), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() - ) - response = await client.list_merchant_center_account_links() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() - ) - - @pytest.mark.asyncio async def test_list_merchant_center_account_links_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1415,7 +1388,7 @@ async def test_list_merchant_center_account_links_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1455,7 +1428,7 @@ async def test_list_merchant_center_account_links_async( request_type=merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest, ): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1531,7 +1504,7 @@ def test_list_merchant_center_account_links_field_headers(): @pytest.mark.asyncio async def test_list_merchant_center_account_links_field_headers_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1609,7 +1582,7 @@ def test_list_merchant_center_account_links_flattened_error(): @pytest.mark.asyncio async def test_list_merchant_center_account_links_flattened_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1642,7 +1615,7 @@ async def test_list_merchant_center_account_links_flattened_async(): @pytest.mark.asyncio async def test_list_merchant_center_account_links_flattened_error_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1691,30 +1664,6 @@ def test_create_merchant_center_account_link(request_type, transport: str = "grp assert isinstance(response, future.Future) -def test_create_merchant_center_account_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_merchant_center_account_link), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_merchant_center_account_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() - ) - - def test_create_merchant_center_account_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1794,32 +1743,6 @@ def test_create_merchant_center_account_link_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_merchant_center_account_link_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_merchant_center_account_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_merchant_center_account_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() - ) - - @pytest.mark.asyncio async def test_create_merchant_center_account_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1828,7 +1751,7 @@ async def test_create_merchant_center_account_link_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1873,7 +1796,7 @@ async def test_create_merchant_center_account_link_async( request_type=merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest, ): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1944,7 +1867,7 @@ def test_create_merchant_center_account_link_field_headers(): @pytest.mark.asyncio async def test_create_merchant_center_account_link_field_headers_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2031,7 +1954,7 @@ def test_create_merchant_center_account_link_flattened_error(): @pytest.mark.asyncio async def test_create_merchant_center_account_link_flattened_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2070,7 +1993,7 @@ async def test_create_merchant_center_account_link_flattened_async(): @pytest.mark.asyncio async def test_create_merchant_center_account_link_flattened_error_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2122,30 +2045,6 @@ def test_delete_merchant_center_account_link(request_type, transport: str = "grp assert response is None -def test_delete_merchant_center_account_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_merchant_center_account_link), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_merchant_center_account_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() - ) - - def test_delete_merchant_center_account_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2220,30 +2119,6 @@ def test_delete_merchant_center_account_link_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_merchant_center_account_link_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_merchant_center_account_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_merchant_center_account_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() - ) - - @pytest.mark.asyncio async def test_delete_merchant_center_account_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2252,7 +2127,7 @@ async def test_delete_merchant_center_account_link_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2292,7 +2167,7 @@ async def test_delete_merchant_center_account_link_async( request_type=merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest, ): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2361,7 +2236,7 @@ def test_delete_merchant_center_account_link_field_headers(): @pytest.mark.asyncio async def test_delete_merchant_center_account_link_field_headers_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2435,7 +2310,7 @@ def test_delete_merchant_center_account_link_flattened_error(): @pytest.mark.asyncio async def test_delete_merchant_center_account_link_flattened_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2464,7 +2339,7 @@ async def test_delete_merchant_center_account_link_flattened_async(): @pytest.mark.asyncio async def test_delete_merchant_center_account_link_flattened_error_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2476,50 +2351,6 @@ async def test_delete_merchant_center_account_link_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest, - dict, - ], -) -def test_list_merchant_center_account_links_rest(request_type): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_merchant_center_account_links(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, - merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse, - ) - - def test_list_merchant_center_account_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2650,115 +2481,27 @@ def test_list_merchant_center_account_links_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_merchant_center_account_links_rest_interceptors(null_interceptor): - transport = transports.MerchantCenterAccountLinkServiceRestTransport( +def test_list_merchant_center_account_links_rest_flattened(): + client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MerchantCenterAccountLinkServiceRestInterceptor(), + transport="rest", ) - client = MerchantCenterAccountLinkServiceClient(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.MerchantCenterAccountLinkServiceRestInterceptor, - "post_list_merchant_center_account_links", - ) as post, mock.patch.object( - transports.MerchantCenterAccountLinkServiceRestInterceptor, - "pre_list_merchant_center_account_links", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest.pb( - merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() - ) - 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 = merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse.to_json( + # 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 = ( merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() ) - request = ( - merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() - ) + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } - client.list_merchant_center_account_links( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_merchant_center_account_links_rest_bad_request( - transport: str = "rest", - request_type=merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest, -): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_merchant_center_account_links(request) - - -def test_list_merchant_center_account_links_rest_flattened(): - client = MerchantCenterAccountLinkServiceClient( - 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 = ( - merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() - ) - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) mock_args.update(sample_request) @@ -2803,134 +2546,6 @@ def test_list_merchant_center_account_links_rest_flattened_error( ) -def test_list_merchant_center_account_links_rest_error(): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest, - dict, - ], -) -def test_create_merchant_center_account_link_rest(request_type): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["merchant_center_account_link"] = { - "name": "name_value", - "id": "id_value", - "merchant_center_account_id": 2730, - "branch_id": "branch_id_value", - "feed_label": "feed_label_value", - "language_code": "language_code_value", - "feed_filters": [ - {"primary_feed_id": 1571, "primary_feed_name": "primary_feed_name_value"} - ], - "state": 1, - "project_id": "project_id_value", - "source": "source_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.meta.fields[ - "merchant_center_account_link" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "merchant_center_account_link" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["merchant_center_account_link"][field]) - ): - del request_init["merchant_center_account_link"][field][i][subfield] - else: - del request_init["merchant_center_account_link"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_merchant_center_account_link(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_merchant_center_account_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3067,127 +2682,39 @@ def test_create_merchant_center_account_link_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_merchant_center_account_link_rest_interceptors(null_interceptor): - transport = transports.MerchantCenterAccountLinkServiceRestTransport( +def test_create_merchant_center_account_link_rest_flattened(): + client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MerchantCenterAccountLinkServiceRestInterceptor(), + transport="rest", ) - client = MerchantCenterAccountLinkServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.MerchantCenterAccountLinkServiceRestInterceptor, - "post_create_merchant_center_account_link", - ) as post, mock.patch.object( - transports.MerchantCenterAccountLinkServiceRestInterceptor, - "pre_create_merchant_center_account_link", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.pb( - merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = ( - merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } - client.create_merchant_center_account_link( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + merchant_center_account_link=gcr_merchant_center_account_link.MerchantCenterAccountLink( + name="name_value" + ), ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_create_merchant_center_account_link_rest_bad_request( - transport: str = "rest", - request_type=merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest, -): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_merchant_center_account_link(request) - - -def test_create_merchant_center_account_link_rest_flattened(): - client = MerchantCenterAccountLinkServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - merchant_center_account_link=gcr_merchant_center_account_link.MerchantCenterAccountLink( - name="name_value" - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_merchant_center_account_link(**mock_args) + client.create_merchant_center_account_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -3220,49 +2747,6 @@ def test_create_merchant_center_account_link_rest_flattened_error( ) -def test_create_merchant_center_account_link_rest_error(): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest, - dict, - ], -) -def test_delete_merchant_center_account_link_rest(request_type): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/merchantCenterAccountLinks/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_merchant_center_account_link(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_merchant_center_account_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3386,85 +2870,6 @@ def test_delete_merchant_center_account_link_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_merchant_center_account_link_rest_interceptors(null_interceptor): - transport = transports.MerchantCenterAccountLinkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MerchantCenterAccountLinkServiceRestInterceptor(), - ) - client = MerchantCenterAccountLinkServiceClient(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.MerchantCenterAccountLinkServiceRestInterceptor, - "pre_delete_merchant_center_account_link", - ) as pre: - pre.assert_not_called() - pb_message = merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest.pb( - merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() - ) - 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() - - request = ( - merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_merchant_center_account_link( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_merchant_center_account_link_rest_bad_request( - transport: str = "rest", - request_type=merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest, -): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/merchantCenterAccountLinks/sample4" - } - 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.delete_merchant_center_account_link(request) - - def test_delete_merchant_center_account_link_rest_flattened(): client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3524,12 +2929,6 @@ def test_delete_merchant_center_account_link_rest_flattened_error( ) -def test_delete_merchant_center_account_link_rest_error(): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.MerchantCenterAccountLinkServiceGrpcTransport( @@ -3582,60 +2981,912 @@ def test_credentials_transport_error(): ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MerchantCenterAccountLinkServiceGrpcTransport( +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MerchantCenterAccountLinkServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MerchantCenterAccountLinkServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MerchantCenterAccountLinkServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MerchantCenterAccountLinkServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MerchantCenterAccountLinkServiceGrpcTransport, + transports.MerchantCenterAccountLinkServiceGrpcAsyncIOTransport, + transports.MerchantCenterAccountLinkServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = MerchantCenterAccountLinkServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_merchant_center_account_links_empty_call_grpc(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_merchant_center_account_links), "__call__" + ) as call: + call.return_value = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() + ) + client.list_merchant_center_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_merchant_center_account_link_empty_call_grpc(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_merchant_center_account_link), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_merchant_center_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_merchant_center_account_link_empty_call_grpc(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_merchant_center_account_link), "__call__" + ) as call: + call.return_value = None + client.delete_merchant_center_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MerchantCenterAccountLinkServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MerchantCenterAccountLinkServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_merchant_center_account_links_empty_call_grpc_asyncio(): + client = MerchantCenterAccountLinkServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_merchant_center_account_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() + ) + await client.list_merchant_center_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_merchant_center_account_link_empty_call_grpc_asyncio(): + client = MerchantCenterAccountLinkServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_merchant_center_account_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_merchant_center_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_merchant_center_account_link_empty_call_grpc_asyncio(): + client = MerchantCenterAccountLinkServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_merchant_center_account_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_merchant_center_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MerchantCenterAccountLinkServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_merchant_center_account_links_rest_bad_request( + request_type=merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest, +): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_merchant_center_account_links(request) + + +@pytest.mark.parametrize( + "request_type", + [ + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest, + dict, + ], +) +def test_list_merchant_center_account_links_rest_call_success(request_type): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_merchant_center_account_links(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse, + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_merchant_center_account_links_rest_interceptors(null_interceptor): + transport = transports.MerchantCenterAccountLinkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MerchantCenterAccountLinkServiceRestInterceptor(), + ) + client = MerchantCenterAccountLinkServiceClient(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.MerchantCenterAccountLinkServiceRestInterceptor, + "post_list_merchant_center_account_links", + ) as post, mock.patch.object( + transports.MerchantCenterAccountLinkServiceRestInterceptor, + "pre_list_merchant_center_account_links", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest.pb( + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse.to_json( + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() + ) + req.return_value.content = return_value + + request = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksResponse() + ) + + client.list_merchant_center_account_links( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_merchant_center_account_link_rest_bad_request( + request_type=merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest, +): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_merchant_center_account_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest, + dict, + ], +) +def test_create_merchant_center_account_link_rest_call_success(request_type): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["merchant_center_account_link"] = { + "name": "name_value", + "id": "id_value", + "merchant_center_account_id": 2730, + "branch_id": "branch_id_value", + "feed_label": "feed_label_value", + "language_code": "language_code_value", + "feed_filters": [ + {"primary_feed_id": 1571, "primary_feed_name": "primary_feed_name_value"} + ], + "state": 1, + "project_id": "project_id_value", + "source": "source_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.meta.fields[ + "merchant_center_account_link" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "merchant_center_account_link" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["merchant_center_account_link"][field]) + ): + del request_init["merchant_center_account_link"][field][i][subfield] + else: + del request_init["merchant_center_account_link"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_merchant_center_account_link(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_merchant_center_account_link_rest_interceptors(null_interceptor): + transport = transports.MerchantCenterAccountLinkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MerchantCenterAccountLinkServiceRestInterceptor(), + ) + client = MerchantCenterAccountLinkServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.MerchantCenterAccountLinkServiceRestInterceptor, + "post_create_merchant_center_account_link", + ) as post, mock.patch.object( + transports.MerchantCenterAccountLinkServiceRestInterceptor, + "pre_create_merchant_center_account_link", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest.pb( + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = ( + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_merchant_center_account_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_merchant_center_account_link_rest_bad_request( + request_type=merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest, +): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/merchantCenterAccountLinks/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_merchant_center_account_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest, + dict, + ], +) +def test_delete_merchant_center_account_link_rest_call_success(request_type): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/merchantCenterAccountLinks/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_merchant_center_account_link(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_merchant_center_account_link_rest_interceptors(null_interceptor): + transport = transports.MerchantCenterAccountLinkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MerchantCenterAccountLinkServiceRestInterceptor(), + ) + client = MerchantCenterAccountLinkServiceClient(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.MerchantCenterAccountLinkServiceRestInterceptor, + "pre_delete_merchant_center_account_link", + ) as pre: + pre.assert_not_called() + pb_message = merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest.pb( + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = ( + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_merchant_center_account_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_merchant_center_account_links_empty_call_rest(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_merchant_center_account_links), "__call__" + ) as call: + client.list_merchant_center_account_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.ListMerchantCenterAccountLinksRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_merchant_center_account_link_empty_call_rest(): + client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = MerchantCenterAccountLinkServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_merchant_center_account_link), "__call__" + ) as call: + client.create_merchant_center_account_link(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MerchantCenterAccountLinkServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.CreateMerchantCenterAccountLinkRequest() + ) - transport = transports.MerchantCenterAccountLinkServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_merchant_center_account_link_empty_call_rest(): + client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_merchant_center_account_link), "__call__" + ) as call: + client.delete_merchant_center_account_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + merchant_center_account_link_service.DeleteMerchantCenterAccountLinkRequest() + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.MerchantCenterAccountLinkServiceGrpcTransport, - transports.MerchantCenterAccountLinkServiceGrpcAsyncIOTransport, - transports.MerchantCenterAccountLinkServiceRestTransport, - ], -) -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() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = MerchantCenterAccountLinkServiceClient.get_transport_class( - transport_name - )( +def test_merchant_center_account_link_service_rest_lro_client(): + client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -3885,23 +4136,6 @@ def test_merchant_center_account_link_service_http_transport_client_cert_source_ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_merchant_center_account_link_service_rest_lro_client(): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -4341,141 +4575,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = MerchantCenterAccountLinkServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4503,7 +4602,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4558,7 +4657,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4605,7 +4704,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -4648,7 +4747,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4703,7 +4802,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4750,7 +4849,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = MerchantCenterAccountLinkServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -4766,22 +4865,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = MerchantCenterAccountLinkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = MerchantCenterAccountLinkServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = MerchantCenterAccountLinkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_model_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_model_service.py index 5877a15d3d71..60e1b5497cbe 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_model_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_model_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2alpha.services.model_service import ( ModelServiceAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.retail_v2alpha.types import model_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1143,25 +1166,6 @@ def test_create_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - def test_create_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1230,27 +1234,6 @@ def test_create_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - @pytest.mark.asyncio async def test_create_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1259,7 +1242,7 @@ async def test_create_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1303,7 +1286,7 @@ async def test_create_model_async( transport: str = "grpc_asyncio", request_type=model_service.CreateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1349,7 @@ def test_create_model_field_headers(): @pytest.mark.asyncio async def test_create_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1453,7 +1436,7 @@ def test_create_model_flattened_error(): @pytest.mark.asyncio async def test_create_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1494,7 +1477,7 @@ async def test_create_model_flattened_async(): @pytest.mark.asyncio async def test_create_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1571,25 +1554,6 @@ def test_get_model(request_type, transport: str = "grpc"): ) -def test_get_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - def test_get_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1653,45 +1617,13 @@ def test_get_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - @pytest.mark.asyncio async def test_get_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1730,7 +1662,7 @@ async def test_get_model_async( transport: str = "grpc_asyncio", request_type=model_service.GetModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1820,7 +1752,7 @@ def test_get_model_field_headers(): @pytest.mark.asyncio async def test_get_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1888,7 +1820,7 @@ def test_get_model_flattened_error(): @pytest.mark.asyncio async def test_get_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1915,7 +1847,7 @@ async def test_get_model_flattened_async(): @pytest.mark.asyncio async def test_get_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1987,25 +1919,6 @@ def test_pause_model(request_type, transport: str = "grpc"): ) -def test_pause_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - def test_pause_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2069,38 +1982,6 @@ def test_pause_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_pause_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - @pytest.mark.asyncio async def test_pause_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2109,7 +1990,7 @@ async def test_pause_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2148,7 +2029,7 @@ async def test_pause_model_async( transport: str = "grpc_asyncio", request_type=model_service.PauseModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2238,7 +2119,7 @@ def test_pause_model_field_headers(): @pytest.mark.asyncio async def test_pause_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2306,7 +2187,7 @@ def test_pause_model_flattened_error(): @pytest.mark.asyncio async def test_pause_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2333,7 +2214,7 @@ async def test_pause_model_flattened_async(): @pytest.mark.asyncio async def test_pause_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2405,25 +2286,6 @@ def test_resume_model(request_type, transport: str = "grpc"): ) -def test_resume_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - def test_resume_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2487,38 +2349,6 @@ def test_resume_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_resume_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - @pytest.mark.asyncio async def test_resume_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2527,7 +2357,7 @@ async def test_resume_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2566,7 +2396,7 @@ async def test_resume_model_async( transport: str = "grpc_asyncio", request_type=model_service.ResumeModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2656,7 +2486,7 @@ def test_resume_model_field_headers(): @pytest.mark.asyncio async def test_resume_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2724,7 +2554,7 @@ def test_resume_model_flattened_error(): @pytest.mark.asyncio async def test_resume_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2751,7 +2581,7 @@ async def test_resume_model_flattened_async(): @pytest.mark.asyncio async def test_resume_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2796,25 +2626,6 @@ def test_delete_model(request_type, transport: str = "grpc"): assert response is None -def test_delete_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - def test_delete_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2878,25 +2689,6 @@ def test_delete_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - @pytest.mark.asyncio async def test_delete_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2905,7 +2697,7 @@ async def test_delete_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2944,7 +2736,7 @@ async def test_delete_model_async( transport: str = "grpc_asyncio", request_type=model_service.DeleteModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3005,7 +2797,7 @@ def test_delete_model_field_headers(): @pytest.mark.asyncio async def test_delete_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3073,7 +2865,7 @@ def test_delete_model_flattened_error(): @pytest.mark.asyncio async def test_delete_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3100,7 +2892,7 @@ async def test_delete_model_flattened_async(): @pytest.mark.asyncio async def test_delete_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3148,25 +2940,6 @@ def test_list_models(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_models_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - def test_list_models_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3232,29 +3005,6 @@ def test_list_models_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_models_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - @pytest.mark.asyncio async def test_list_models_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3263,7 +3013,7 @@ async def test_list_models_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3302,7 +3052,7 @@ async def test_list_models_async( transport: str = "grpc_asyncio", request_type=model_service.ListModelsRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3368,7 +3118,7 @@ def test_list_models_field_headers(): @pytest.mark.asyncio async def test_list_models_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3438,7 +3188,7 @@ def test_list_models_flattened_error(): @pytest.mark.asyncio async def test_list_models_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3467,7 +3217,7 @@ async def test_list_models_flattened_async(): @pytest.mark.asyncio async def test_list_models_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3577,7 +3327,7 @@ def test_list_models_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_models_async_pager(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3627,7 +3377,7 @@ async def test_list_models_async_pager(): @pytest.mark.asyncio async def test_list_models_async_pages(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3733,25 +3483,6 @@ def test_update_model(request_type, transport: str = "grpc"): ) -def test_update_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - def test_update_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3811,38 +3542,6 @@ def test_update_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - @pytest.mark.asyncio async def test_update_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3851,7 +3550,7 @@ async def test_update_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3890,7 +3589,7 @@ async def test_update_model_async( transport: str = "grpc_asyncio", request_type=model_service.UpdateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3980,7 +3679,7 @@ def test_update_model_field_headers(): @pytest.mark.asyncio async def test_update_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4065,7 +3764,7 @@ def test_update_model_flattened_error(): @pytest.mark.asyncio async def test_update_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4104,7 +3803,7 @@ async def test_update_model_flattened_async(): @pytest.mark.asyncio async def test_update_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4154,25 +3853,6 @@ def test_tune_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_tune_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - def test_tune_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4241,34 +3921,13 @@ def test_tune_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_tune_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - @pytest.mark.asyncio async def test_tune_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4312,7 +3971,7 @@ async def test_tune_model_async( transport: str = "grpc_asyncio", request_type=model_service.TuneModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4375,7 +4034,7 @@ def test_tune_model_field_headers(): @pytest.mark.asyncio async def test_tune_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4445,7 +4104,7 @@ def test_tune_model_flattened_error(): @pytest.mark.asyncio async def test_tune_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4474,7 +4133,7 @@ async def test_tune_model_flattened_async(): @pytest.mark.asyncio async def test_tune_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4486,148 +4145,6 @@ async def test_tune_model_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - model_service.CreateModelRequest, - dict, - ], -) -def test_create_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["model"] = { - "page_optimization_config": { - "page_optimization_event_type": "page_optimization_event_type_value", - "panels": [ - { - "display_name": "display_name_value", - "candidates": [{"serving_config_id": "serving_config_id_value"}], - "default_candidate": {}, - } - ], - "restriction": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1}, - "llm_embedding_config": { - "llm_embedding_version": "llm_embedding_version_value" - }, - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.CreateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4759,93 +4276,10 @@ def test_create_model_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_create_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_create_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_create_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.CreateModelRequest.pb( - model_service.CreateModelRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.CreateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_model_rest_bad_request( - transport: str = "rest", request_type=model_service.CreateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_model(request) - - -def test_create_model_rest_flattened(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -4909,78 +4343,6 @@ def test_create_model_rest_flattened_error(transport: str = "rest"): ) -def test_create_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.GetModelRequest, - dict, - ], -) -def test_get_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_get_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5098,85 +4460,6 @@ def test_get_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_get_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) - 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 = model.Model.to_json(model.Model()) - - request = model_service.GetModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.get_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_model_rest_bad_request( - transport: str = "rest", request_type=model_service.GetModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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_model(request) - - def test_get_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5236,100 +4519,28 @@ def test_get_model_rest_flattened_error(transport: str = "rest"): ) -def test_get_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_pause_model_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - model_service.PauseModelRequest, - dict, - ], -) -def test_pause_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert client._transport.pause_model in client._transport._wrapped_methods - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.pause_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - -def test_pause_model_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.pause_model in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc request = {} client.pause_model(request) @@ -5426,87 +4637,6 @@ def test_pause_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_pause_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_pause_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.PauseModelRequest.pb( - model_service.PauseModelRequest() - ) - 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 = model.Model.to_json(model.Model()) - - request = model_service.PauseModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.pause_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_pause_model_rest_bad_request( - transport: str = "rest", request_type=model_service.PauseModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.pause_model(request) - - def test_pause_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5566,78 +4696,6 @@ def test_pause_model_rest_flattened_error(transport: str = "rest"): ) -def test_pause_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ResumeModelRequest, - dict, - ], -) -def test_resume_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.resume_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_resume_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5758,102 +4816,21 @@ def test_resume_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_resume_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_resume_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_resume_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ResumeModelRequest.pb( - model_service.ResumeModelRequest() - ) - 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 = model.Model.to_json(model.Model()) + # 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 = model.Model() - request = model_service.ResumeModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.resume_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_resume_model_rest_bad_request( - transport: str = "rest", request_type=model_service.ResumeModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.resume_model(request) - - -def test_resume_model_rest_flattened(): - client = ModelServiceClient( - 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 = model.Model() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -5898,49 +4875,6 @@ def test_resume_model_rest_flattened_error(transport: str = "rest"): ) -def test_resume_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.DeleteModelRequest, - dict, - ], -) -def test_delete_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_model(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6057,81 +4991,6 @@ def test_delete_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" - ) as pre: - pre.assert_not_called() - pb_message = model_service.DeleteModelRequest.pb( - model_service.DeleteModelRequest() - ) - 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() - - request = model_service.DeleteModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_model_rest_bad_request( - transport: str = "rest", request_type=model_service.DeleteModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.delete_model(request) - - def test_delete_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6189,52 +5048,6 @@ def test_delete_model_rest_flattened_error(transport: str = "rest"): ) -def test_delete_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ListModelsRequest, - dict, - ], -) -def test_list_models_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model_service.ListModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_models(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListModelsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_models_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6367,108 +5180,27 @@ def test_list_models_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_models_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_list_models_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_list_models" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ListModelsRequest.pb( - model_service.ListModelsRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = model_service.ListModelsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = model_service.ListModelsResponse.to_json( - model_service.ListModelsResponse() + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - - request = model_service.ListModelsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model_service.ListModelsResponse() - - client.list_models( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_models_rest_bad_request( - transport: str = "rest", request_type=model_service.ListModelsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_models(request) - - -def test_list_models_rest_flattened(): - client = ModelServiceClient( - 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 = model_service.ListModelsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6570,181 +5302,6 @@ def test_list_models_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - model_service.UpdateModelRequest, - dict, - ], -) -def test_update_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - request_init["model"] = { - "page_optimization_config": { - "page_optimization_event_type": "page_optimization_event_type_value", - "panels": [ - { - "display_name": "display_name_value", - "candidates": [{"serving_config_id": "serving_config_id_value"}], - "default_candidate": {}, - } - ], - "restriction": 1, - }, - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1}, - "llm_embedding_config": { - "llm_embedding_version": "llm_embedding_version_value" - }, - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.UpdateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == gcr_model.Model.TrainingState.PAUSED - assert response.serving_state == gcr_model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == gcr_model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_update_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6862,93 +5419,10 @@ def test_update_model_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("model",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_update_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_update_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.UpdateModelRequest.pb( - model_service.UpdateModelRequest() - ) - 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 = gcr_model.Model.to_json(gcr_model.Model()) - - request = model_service.UpdateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_model.Model() - - client.update_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_model_rest_bad_request( - transport: str = "rest", request_type=model_service.UpdateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - 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_model(request) - - -def test_update_model_rest_flattened(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7016,49 +5490,6 @@ def test_update_model_rest_flattened_error(transport: str = "rest"): ) -def test_update_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.TuneModelRequest, - dict, - ], -) -def test_tune_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.tune_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_tune_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7178,89 +5609,6 @@ def test_tune_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_tune_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_tune_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_tune_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.TuneModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.tune_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_tune_model_rest_bad_request( - transport: str = "rest", request_type=model_service.TuneModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.tune_model(request) - - def test_tune_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7318,12 +5666,6 @@ def test_tune_model_rest_flattened_error(transport: str = "rest"): ) -def test_tune_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ModelServiceGrpcTransport( @@ -7376,58 +5718,2051 @@ def test_credentials_transport_error(): ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ModelServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ModelServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ModelServiceGrpcTransport, + transports.ModelServiceGrpcAsyncIOTransport, + transports.ModelServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ModelServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + call.return_value = model.Model() + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + call.return_value = model.Model() + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + call.return_value = model.Model() + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + call.return_value = None + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + call.return_value = model_service.ListModelsResponse() + client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + call.return_value = gcr_model.Model() + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ModelServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_pause_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_resume_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_models_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_tune_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ModelServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_model_rest_bad_request(request_type=model_service.CreateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.CreateModelRequest, + dict, + ], +) +def test_create_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["model"] = { + "page_optimization_config": { + "page_optimization_event_type": "page_optimization_event_type_value", + "panels": [ + { + "display_name": "display_name_value", + "candidates": [{"serving_config_id": "serving_config_id_value"}], + "default_candidate": {}, + } + ], + "restriction": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1}, + "llm_embedding_config": { + "llm_embedding_version": "llm_embedding_version_value" + }, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.CreateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_create_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_create_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.CreateModelRequest.pb( + model_service.CreateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.CreateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_model_rest_bad_request(request_type=model_service.GetModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.GetModelRequest, + dict, + ], +) +def test_get_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_get_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.GetModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.get_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_pause_model_rest_bad_request(request_type=model_service.PauseModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.pause_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.PauseModelRequest, + dict, + ], +) +def test_pause_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.pause_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_pause_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.PauseModelRequest.pb( + model_service.PauseModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.PauseModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.pause_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resume_model_rest_bad_request(request_type=model_service.ResumeModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.resume_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ResumeModelRequest, + dict, + ], +) +def test_resume_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.resume_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_resume_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ResumeModelRequest.pb( + model_service.ResumeModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.ResumeModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.resume_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_model_rest_bad_request(request_type=model_service.DeleteModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.DeleteModelRequest, + dict, + ], +) +def test_delete_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_model(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" + ) as pre: + pre.assert_not_called() + pb_message = model_service.DeleteModelRequest.pb( + model_service.DeleteModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = model_service.DeleteModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_models_rest_bad_request(request_type=model_service.ListModelsRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_models(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ListModelsRequest, + dict, + ], +) +def test_list_models_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model_service.ListModelsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_models(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListModelsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_models_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_list_models" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ListModelsRequest.pb( + model_service.ListModelsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model_service.ListModelsResponse.to_json( + model_service.ListModelsResponse() + ) + req.return_value.content = return_value + + request = model_service.ListModelsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model_service.ListModelsResponse() + + client.list_models( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_model_rest_bad_request(request_type=model_service.UpdateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.UpdateModelRequest, + dict, + ], +) +def test_update_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + request_init["model"] = { + "page_optimization_config": { + "page_optimization_event_type": "page_optimization_event_type_value", + "panels": [ + { + "display_name": "display_name_value", + "candidates": [{"serving_config_id": "serving_config_id_value"}], + "default_candidate": {}, + } + ], + "restriction": 1, + }, + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1}, + "llm_embedding_config": { + "llm_embedding_version": "llm_embedding_version_value" + }, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.UpdateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == gcr_model.Model.TrainingState.PAUSED + assert response.serving_state == gcr_model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == gcr_model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_update_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.UpdateModelRequest.pb( + model_service.UpdateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_model.Model.to_json(gcr_model.Model()) + req.return_value.content = return_value + + request = model_service.UpdateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_model.Model() + + client.update_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tune_model_rest_bad_request(request_type=model_service.TuneModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.tune_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.TuneModelRequest, + dict, + ], +) +def test_tune_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.tune_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tune_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_tune_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_tune_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.TuneModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.tune_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ModelServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + client.list_models(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ModelServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + client.tune_model(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ModelServiceGrpcTransport, - transports.ModelServiceGrpcAsyncIOTransport, - transports.ModelServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ModelServiceClient.get_transport_class(transport_name)( + +def test_model_service_rest_lro_client(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7670,23 +8005,6 @@ def test_model_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_model_service_rest_lro_client(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8109,141 +8427,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8271,7 +8454,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8326,7 +8509,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8373,7 +8556,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8416,7 +8599,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8471,7 +8654,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8518,7 +8701,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8534,22 +8717,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_prediction_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_prediction_service.py index 68f22306b4ea..d983c0817d60 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_prediction_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_prediction_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -38,17 +55,9 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -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.retail_v2alpha.services.prediction_service import ( PredictionServiceAsyncClient, @@ -64,10 +73,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1207,25 +1230,6 @@ def test_predict(request_type, transport: str = "grpc"): assert response.validate_only is True -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - def test_predict_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1293,38 +1297,13 @@ def test_predict_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_predict_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - ) - response = await client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - @pytest.mark.asyncio async def test_predict_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1363,7 +1342,7 @@ async def test_predict_async( transport: str = "grpc_asyncio", request_type=prediction_service.PredictRequest ): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_predict_field_headers(): @pytest.mark.asyncio async def test_predict_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,52 +1441,6 @@ async def test_predict_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - prediction_service.PredictRequest, - dict, - ], -) -def test_predict_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = prediction_service.PredictResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.predict(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == "attribution_token_value" - assert response.missing_ids == ["missing_ids_value"] - assert response.validate_only is True - - def test_predict_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1634,95 +1567,6 @@ def test_predict_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_predict_rest_interceptors(null_interceptor): - transport = transports.PredictionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionServiceRestInterceptor(), - ) - client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" - ) as post, mock.patch.object( - transports.PredictionServiceRestInterceptor, "pre_predict" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_service.PredictRequest.pb( - prediction_service.PredictRequest() - ) - 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 = prediction_service.PredictResponse.to_json( - prediction_service.PredictResponse() - ) - - request = prediction_service.PredictRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = prediction_service.PredictResponse() - - client.predict( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_predict_rest_bad_request( - transport: str = "rest", request_type=prediction_service.PredictRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.predict(request) - - -def test_predict_rest_error(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PredictionServiceGrpcTransport( @@ -1815,80 +1659,430 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = PredictionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request=None) -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + assert args[0] == request_msg -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "predict", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = PredictionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" - ) as Transport: +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_predict_empty_call_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + ) + await client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PredictionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_predict_rest_bad_request(request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.predict(request) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_service.PredictRequest, + dict, + ], +) +def test_predict_rest_call_success(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.predict(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == "attribution_token_value" + assert response.missing_ids == ["missing_ids_value"] + assert response.validate_only is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_predict_rest_interceptors(null_interceptor): + transport = transports.PredictionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionServiceRestInterceptor(), + ) + client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" + ) as post, mock.patch.object( + transports.PredictionServiceRestInterceptor, "pre_predict" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_service.PredictRequest.pb( + prediction_service.PredictRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = prediction_service.PredictResponse.to_json( + prediction_service.PredictResponse() + ) + req.return_value.content = return_value + + request = prediction_service.PredictRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_service.PredictResponse() + + client.predict( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "predict", + "get_operation", + "list_operations", + ) + 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_prediction_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.retail_v2alpha.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionServiceTransport( @@ -2414,141 +2608,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2576,7 +2635,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2631,7 +2690,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2678,7 +2737,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2721,7 +2780,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2776,7 +2835,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2823,7 +2882,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2839,22 +2898,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_product_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_product_service.py index b4393dedd311..8678fc4a3b2f 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_product_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_product_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,17 +64,9 @@ from google.oauth2 import service_account from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2alpha.services.product_service import ( ProductServiceAsyncClient, @@ -71,10 +80,24 @@ from google.cloud.retail_v2alpha.types import product as gcr_product +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1206,25 +1229,6 @@ def test_create_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - def test_create_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,46 +1294,6 @@ def test_create_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - @pytest.mark.asyncio async def test_create_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1338,7 +1302,7 @@ async def test_create_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1377,7 +1341,7 @@ async def test_create_product_async( transport: str = "grpc_asyncio", request_type=product_service.CreateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1477,7 +1441,7 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1559,7 +1523,7 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1596,7 +1560,7 @@ async def test_create_product_flattened_async(): @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1682,25 +1646,6 @@ def test_get_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - def test_get_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1764,46 +1709,6 @@ def test_get_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product.Product( - name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - @pytest.mark.asyncio async def test_get_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1812,7 +1717,7 @@ async def test_get_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1851,7 +1756,7 @@ async def test_get_product_async( transport: str = "grpc_asyncio", request_type=product_service.GetProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1951,7 +1856,7 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2019,7 +1924,7 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1951,7 @@ async def test_get_product_flattened_async(): @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2096,25 +2001,6 @@ def test_list_products(request_type, transport: str = "grpc"): assert response.total_size == 1086 -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - def test_list_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2182,30 +2068,6 @@ def test_list_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_service.ListProductsResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - ) - response = await client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - @pytest.mark.asyncio async def test_list_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2214,7 +2076,7 @@ async def test_list_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2253,7 +2115,7 @@ async def test_list_products_async( transport: str = "grpc_asyncio", request_type=product_service.ListProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2321,7 +2183,7 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2391,7 +2253,7 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2420,7 +2282,7 @@ async def test_list_products_flattened_async(): @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2530,7 +2392,7 @@ def test_list_products_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2580,7 +2442,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2696,25 +2558,6 @@ def test_update_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - def test_update_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2774,46 +2617,6 @@ def test_update_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - @pytest.mark.asyncio async def test_update_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2822,7 +2625,7 @@ async def test_update_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2861,7 +2664,7 @@ async def test_update_product_async( transport: str = "grpc_asyncio", request_type=product_service.UpdateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2961,7 +2764,7 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3038,7 +2841,7 @@ def test_update_product_flattened_error(): @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3071,7 +2874,7 @@ async def test_update_product_flattened_async(): @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3119,25 +2922,6 @@ def test_delete_product(request_type, transport: str = "grpc"): assert response is None -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - def test_delete_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3202,35 +2986,16 @@ def test_delete_product_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - -@pytest.mark.asyncio -async def test_delete_product_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_delete_product_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3267,7 +3032,7 @@ async def test_delete_product_async( transport: str = "grpc_asyncio", request_type=product_service.DeleteProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3328,7 +3093,7 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3396,7 +3161,7 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3423,7 +3188,7 @@ async def test_delete_product_flattened_async(): @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3468,25 +3233,6 @@ def test_purge_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - def test_purge_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3557,27 +3303,6 @@ def test_purge_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - @pytest.mark.asyncio async def test_purge_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3586,7 +3311,7 @@ async def test_purge_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3630,7 +3355,7 @@ async def test_purge_products_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3693,7 +3418,7 @@ def test_purge_products_field_headers(): @pytest.mark.asyncio async def test_purge_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3755,25 +3480,6 @@ def test_import_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - def test_import_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3846,27 +3552,6 @@ def test_import_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - @pytest.mark.asyncio async def test_import_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3875,7 +3560,7 @@ async def test_import_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3919,7 +3604,7 @@ async def test_import_products_async( transport: str = "grpc_asyncio", request_type=import_config.ImportProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3982,7 +3667,7 @@ def test_import_products_field_headers(): @pytest.mark.asyncio async def test_import_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4044,25 +3729,6 @@ def test_export_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportProductsRequest() - - def test_export_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4133,27 +3799,6 @@ def test_export_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportProductsRequest() - - @pytest.mark.asyncio async def test_export_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4162,7 +3807,7 @@ async def test_export_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4206,7 +3851,7 @@ async def test_export_products_async( transport: str = "grpc_asyncio", request_type=export_config.ExportProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4269,7 +3914,7 @@ def test_export_products_field_headers(): @pytest.mark.asyncio async def test_export_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4331,25 +3976,6 @@ def test_set_inventory(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - def test_set_inventory_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4414,27 +4040,6 @@ def test_set_inventory_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_inventory_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - @pytest.mark.asyncio async def test_set_inventory_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4443,7 +4048,7 @@ async def test_set_inventory_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4487,7 +4092,7 @@ async def test_set_inventory_async( transport: str = "grpc_asyncio", request_type=product_service.SetInventoryRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4550,7 +4155,7 @@ def test_set_inventory_field_headers(): @pytest.mark.asyncio async def test_set_inventory_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4625,7 +4230,7 @@ def test_set_inventory_flattened_error(): @pytest.mark.asyncio async def test_set_inventory_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4658,7 +4263,7 @@ async def test_set_inventory_flattened_async(): @pytest.mark.asyncio async def test_set_inventory_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4706,27 +4311,6 @@ def test_add_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - def test_add_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4804,29 +4388,6 @@ def test_add_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4835,7 +4396,7 @@ async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4880,7 +4441,7 @@ async def test_add_fulfillment_places_async( request_type=product_service.AddFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4947,7 +4508,7 @@ def test_add_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_add_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5021,7 +4582,7 @@ def test_add_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5052,7 +4613,7 @@ async def test_add_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5099,27 +4660,6 @@ def test_remove_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - def test_remove_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5197,29 +4737,6 @@ def test_remove_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5228,7 +4745,7 @@ async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5273,7 +4790,7 @@ async def test_remove_fulfillment_places_async( request_type=product_service.RemoveFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5340,7 +4857,7 @@ def test_remove_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_remove_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5414,7 +4931,7 @@ def test_remove_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5445,7 +4962,7 @@ async def test_remove_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5492,27 +5009,6 @@ def test_add_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - def test_add_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5588,29 +5084,6 @@ def test_add_local_inventories_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - @pytest.mark.asyncio async def test_add_local_inventories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5619,7 +5092,7 @@ async def test_add_local_inventories_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5664,7 +5137,7 @@ async def test_add_local_inventories_async( request_type=product_service.AddLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5731,7 +5204,7 @@ def test_add_local_inventories_field_headers(): @pytest.mark.asyncio async def test_add_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5805,7 +5278,7 @@ def test_add_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5836,7 +5309,7 @@ async def test_add_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5883,27 +5356,6 @@ def test_remove_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - def test_remove_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5979,29 +5431,6 @@ def test_remove_local_inventories_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - @pytest.mark.asyncio async def test_remove_local_inventories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6010,7 +5439,7 @@ async def test_remove_local_inventories_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6055,7 +5484,7 @@ async def test_remove_local_inventories_async( request_type=product_service.RemoveLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6122,7 +5551,7 @@ def test_remove_local_inventories_field_headers(): @pytest.mark.asyncio async def test_remove_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6196,7 +5625,7 @@ def test_remove_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6227,7 +5656,7 @@ async def test_remove_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6239,278 +5668,55 @@ async def test_remove_local_inventories_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - product_service.CreateProductRequest, - dict, - ], -) -def test_create_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = product_service.CreateProductRequest.meta.fields["product"] + # Ensure method has been cached + assert client._transport.create_product in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_product] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_product(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.create_product(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +def test_create_product_rest_required_fields( + request_type=product_service.CreateProductRequest, +): + transport_class = transports.ProductServiceRestTransport - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] + request_init = {} + request_init["parent"] = "" + request_init["product_id"] = "" 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - -def test_create_product_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_product] = mock_rpc - - request = {} - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_product(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_product_rest_required_fields( - request_type=product_service.CreateProductRequest, -): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["product_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped assert "productId" not in jsonified_request @@ -6606,87 +5812,6 @@ def test_create_product_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_create_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.CreateProductRequest.pb( - product_service.CreateProductRequest() - ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) - - request = product_service.CreateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() - - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_product_rest_bad_request( - transport: str = "rest", request_type=product_service.CreateProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.create_product(request) - - def test_create_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6754,54 +5879,146 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): ) -def test_create_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_get_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_product in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_product] = mock_rpc + + request = {} + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_product(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_product_rest_required_fields( + request_type=product_service.GetProductRequest, +): + transport_class = transports.ProductServiceRestTransport + + 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, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_product._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_product._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" -@pytest.mark.parametrize( - "request_type", - [ - product_service.GetProductRequest, - dict, - ], -) -def test_get_product_rest(request_type): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = product.Product() + # 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 + + # Convert return value to protobuf type + return_value = product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_product(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_product_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_product._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_product_rest_flattened(): + client = ProductServiceClient( + 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 = product.Product( + return_value = product.Product() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6809,34 +6026,38 @@ def test_get_product_rest(request_type): # Convert return value to protobuf type return_value = product.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_product(request) - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] + client.get_product(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}" + % client.transport._host, + args[1], + ) -def test_get_product_rest_use_cached_wrapped_rpc(): +def test_get_product_rest_flattened_error(transport: str = "rest"): + client = ProductServiceClient( + 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_product( + product_service.GetProductRequest(), + name="name_value", + ) + + +def test_list_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6850,35 +6071,35 @@ def test_get_product_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_product in client._transport._wrapped_methods + assert client._transport.list_products in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_product] = mock_rpc + client._transport._wrapped_methods[client._transport.list_products] = mock_rpc request = {} - client.get_product(request) + client.list_products(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_product(request) + client.list_products(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_product_rest_required_fields( - request_type=product_service.GetProductRequest, +def test_list_products_rest_required_fields( + request_type=product_service.ListProductsRequest, ): transport_class = transports.ProductServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6889,21 +6110,31 @@ def test_get_product_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + ).list_products._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_product._get_unset_required_fields(jsonified_request) + ).list_products._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "read_mask", + "require_total_size", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6912,7 +6143,7 @@ def test_get_product_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = product.Product() + return_value = product_service.ListProductsResponse() # 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 @@ -6933,154 +6164,84 @@ def test_get_product_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = product.Product.pb(return_value) + return_value = product_service.ListProductsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_product(request) + response = client.list_products(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_product_rest_unset_required_fields(): +def test_list_products_rest_unset_required_fields(): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_products._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "readMask", + "requireTotalSize", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_list_products_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), + transport="rest", ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_get_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.GetProductRequest.pb( - product_service.GetProductRequest() - ) - 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 = product.Product.to_json(product.Product()) + # 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 = product_service.ListProductsResponse() - request = product_service.GetProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product.Product() + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = product_service.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_get_product_rest_bad_request( - transport: str = "rest", request_type=product_service.GetProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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_product(request) - - -def test_get_product_rest_flattened(): - client = ProductServiceClient( - 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 = product.Product() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - - # 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 - # Convert return value to protobuf type - return_value = product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_product(**mock_args) + client.list_products(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}" + "%s/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products" % client.transport._host, args[1], ) -def test_get_product_rest_flattened_error(transport: str = "rest"): +def test_list_products_rest_flattened_error(transport: str = "rest"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7089,63 +6250,78 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_product( - product_service.GetProductRequest(), - name="name_value", + client.list_products( + product_service.ListProductsRequest(), + parent="parent_value", ) -def test_get_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.ListProductsRequest, - dict, - ], -) -def test_list_products_rest(request_type): +def test_list_products_rest_pager(transport: str = "rest"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = product_service.ListProductsResponse( - next_page_token="next_page_token_value", - total_size=1086, + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + product.Product(), + ], + next_page_token="abc", + ), + product_service.ListProductsResponse( + products=[], + next_page_token="def", + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + ], + next_page_token="ghi", + ), + product_service.ListProductsResponse( + products=[ + product.Product(), + product.Product(), + ], + ), ) + # Two responses for two calls + response = response + response - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product_service.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Wrap the values into proper Response objs + response = tuple( + product_service.ListProductsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_products(request) + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + pager = client.list_products(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, product.Product) for i in results) + + pages = list(client.list_products(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_products_rest_use_cached_wrapped_rpc(): +def test_update_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7159,35 +6335,34 @@ def test_list_products_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_products in client._transport._wrapped_methods + assert client._transport.update_product in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_products] = mock_rpc + client._transport._wrapped_methods[client._transport.update_product] = mock_rpc request = {} - client.list_products(request) + client.update_product(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_products(request) + client.update_product(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_products_rest_required_fields( - request_type=product_service.ListProductsRequest, +def test_update_product_rest_required_fields( + request_type=product_service.UpdateProductRequest, ): transport_class = transports.ProductServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7198,31 +6373,24 @@ def test_list_products_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_products._get_unset_required_fields(jsonified_request) + ).update_product._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() - ).list_products._get_unset_required_fields(jsonified_request) + ).update_product._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "page_size", - "page_token", - "read_mask", - "require_total_size", + "allow_missing", + "update_mask", ) ) 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 = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7231,7 +6399,7 @@ def test_list_products_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = product_service.ListProductsResponse() + return_value = gcr_product.Product() # 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 @@ -7243,132 +6411,232 @@ def test_list_products_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = product_service.ListProductsResponse.pb(return_value) + return_value = gcr_product.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_products(request) + response = client.update_product(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_products_rest_unset_required_fields(): +def test_update_product_rest_unset_required_fields(): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_products._get_unset_required_fields({}) + unset_fields = transport.update_product._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "pageSize", - "pageToken", - "readMask", - "requireTotalSize", + "allowMissing", + "updateMask", ) ) - & set(("parent",)) + & set(("product",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_update_product_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), + transport="rest", ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_list_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.ListProductsRequest.pb( - product_service.ListProductsRequest() - ) - 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 = product_service.ListProductsResponse.to_json( - product_service.ListProductsResponse() - ) - request = product_service.ListProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product_service.ListProductsResponse() + # 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 = gcr_product.Product() - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get arguments that satisfy an http rule for this method + sample_request = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + product=gcr_product.Product( + expire_time=timestamp_pb2.Timestamp(seconds=751) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + client.update_product(**mock_args) -def test_list_products_rest_bad_request( - transport: str = "rest", request_type=product_service.ListProductsRequest -): + # 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/v2alpha/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}" + % client.transport._host, + args[1], + ) + + +def test_update_product_rest_flattened_error(transport: str = "rest"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product( + product_service.UpdateProductRequest(), + product=gcr_product.Product( + expire_time=timestamp_pb2.Timestamp(seconds=751) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_product in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc + + request = {} + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_product(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_product_rest_required_fields( + request_type=product_service.DeleteProductRequest, +): + transport_class = transports.ProductServiceRestTransport + + 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, use_integers_for_enums=False) + ) - # 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.list_products(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_product._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_list_products_rest_flattened(): + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_product._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + 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 = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_product(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_product_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_product._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +def test_delete_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7377,42 +6645,40 @@ def test_list_products_rest_flattened(): # 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 = product_service.ListProductsResponse() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product_service.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_products(**mock_args) + client.delete_product(**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/v2alpha/{parent=projects/*/locations/*/catalogs/*/branches/*}/products" + "%s/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}" % client.transport._host, args[1], ) -def test_list_products_rest_flattened_error(transport: str = "rest"): +def test_delete_product_rest_flattened_error(transport: str = "rest"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7421,303 +6687,146 @@ def test_list_products_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_products( - product_service.ListProductsRequest(), - parent="parent_value", + client.delete_product( + product_service.DeleteProductRequest(), + name="name_value", ) -def test_list_products_rest_pager(transport: str = "rest"): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - product.Product(), - ], - next_page_token="abc", - ), - product_service.ListProductsResponse( - products=[], - next_page_token="def", - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - ], - next_page_token="ghi", - ), - product_service.ListProductsResponse( - products=[ - product.Product(), - product.Product(), - ], - ), +def test_purge_products_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - product_service.ListProductsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } + # Ensure method has been cached + assert client._transport.purge_products in client._transport._wrapped_methods - pager = client.list_products(request=sample_request) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, product.Product) for i in results) + request = {} + client.purge_products(request) - pages = list(client.list_products(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + client.purge_products(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_purge_products_rest_required_fields( + request_type=purge_config.PurgeProductsRequest, +): + transport_class = transports.ProductServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).purge_products._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" + jsonified_request["filter"] = "filter_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).purge_products._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" + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_value" -@pytest.mark.parametrize( - "request_type", - [ - product_service.UpdateProductRequest, - dict, - ], -) -def test_update_product_rest(request_type): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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, } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - # Determine if the message type is proto-plus or protobuf - test_field = product_service.UpdateProductRequest.meta.fields["product"] + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response = client.purge_products(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_purge_products_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + unset_fields = transport.purge_products._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "filter", + ) + ) + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] - 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - -def test_update_product_rest_use_cached_wrapped_rpc(): +def test_import_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7731,34 +6840,39 @@ def test_update_product_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_product in client._transport._wrapped_methods + assert client._transport.import_products in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_product] = mock_rpc + client._transport._wrapped_methods[client._transport.import_products] = mock_rpc request = {} - client.update_product(request) + client.import_products(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_product(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_products(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_product_rest_required_fields( - request_type=product_service.UpdateProductRequest, +def test_import_products_rest_required_fields( + request_type=import_config.ImportProductsRequest, ): transport_class = transports.ProductServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7769,24 +6883,21 @@ def test_update_product_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_product._get_unset_required_fields(jsonified_request) + ).import_products._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() - ).update_product._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "update_mask", - ) - ) + ).import_products._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 = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7795,7 +6906,7 @@ def test_update_product_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_product.Product() + return_value = operations_pb2.Operation(name="operations/spam") # 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 @@ -7807,7 +6918,7 @@ def test_update_product_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -7815,232 +6926,165 @@ def test_update_product_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_product(request) + response = client.import_products(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_product_rest_unset_required_fields(): +def test_import_products_rest_unset_required_fields(): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_product._get_unset_required_fields({}) + unset_fields = transport.import_products._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "allowMissing", - "updateMask", + "parent", + "inputConfig", ) ) - & set(("product",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_update_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.UpdateProductRequest.pb( - product_service.UpdateProductRequest() +def test_export_products_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - request = product_service.UpdateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() + # Ensure method has been cached + assert client._transport.export_products in client._transport._wrapped_methods - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.export_products] = mock_rpc - pre.assert_called_once() - post.assert_called_once() + request = {} + client.export_products(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_update_product_rest_bad_request( - transport: str = "rest", request_type=product_service.UpdateProductRequest + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_products(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_export_products_rest_required_fields( + request_type=export_config.ExportProductsRequest, ): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + transport_class = transports.ProductServiceRestTransport - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } + 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, use_integers_for_enums=False) + ) - # 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_product(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_products._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() + ).export_products._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_update_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") # 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 = gcr_product.Product() - - # get arguments that satisfy an http rule for this method - sample_request = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + 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 - # get truthy value for each flattened field - mock_args = dict( - product=gcr_product.Product( - expire_time=timestamp_pb2.Timestamp(seconds=751) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.update_product(**mock_args) + response = client.export_products(request) - # 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/v2alpha/{product.name=projects/*/locations/*/catalogs/*/branches/*/products/**}" - % client.transport._host, - args[1], - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -def test_update_product_rest_flattened_error(transport: str = "rest"): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_export_products_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_product( - product_service.UpdateProductRequest(), - product=gcr_product.Product( - expire_time=timestamp_pb2.Timestamp(seconds=751) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + unset_fields = transport.export_products._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "outputConfig", + ) ) - - -def test_update_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_product(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_product_rest_use_cached_wrapped_rpc(): +def test_set_inventory_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8054,35 +7098,38 @@ def test_delete_product_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_product in client._transport._wrapped_methods + assert client._transport.set_inventory in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_product] = mock_rpc + client._transport._wrapped_methods[client._transport.set_inventory] = mock_rpc request = {} - client.delete_product(request) + client.set_inventory(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_product(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_inventory(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_product_rest_required_fields( - request_type=product_service.DeleteProductRequest, +def test_set_inventory_rest_required_fields( + request_type=product_service.SetInventoryRequest, ): transport_class = transports.ProductServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8093,23 +7140,17 @@ def test_delete_product_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_product._get_unset_required_fields(jsonified_request) + ).set_inventory._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() - ).delete_product._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force",)) + ).set_inventory._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 = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8118,7 +7159,7 @@ def test_delete_product_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = operations_pb2.Operation(name="operations/spam") # 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 @@ -8130,110 +7171,36 @@ def test_delete_product_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_product(request) + response = client.set_inventory(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_product_rest_unset_required_fields(): +def test_set_inventory_rest_unset_required_fields(): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_product._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force",)) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "pre_delete_product" - ) as pre: - pre.assert_not_called() - pb_message = product_service.DeleteProductRequest.pb( - product_service.DeleteProductRequest() - ) - 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() - - request = product_service.DeleteProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_product_rest_bad_request( - transport: str = "rest", request_type=product_service.DeleteProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.delete_product(request) + unset_fields = transport.set_inventory._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("inventory",))) -def test_delete_product_rest_flattened(): +def test_set_inventory_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8242,40 +7209,43 @@ def test_delete_product_rest_flattened(): # 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 = None + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_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 - json_return_value = "" + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_product(**mock_args) + client.set_inventory(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/branches/*/products/**}" + "%s/v2alpha/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory" % client.transport._host, args[1], ) -def test_delete_product_rest_flattened_error(transport: str = "rest"): +def test_set_inventory_rest_flattened_error(transport: str = "rest"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8284,56 +7254,214 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_product( - product_service.DeleteProductRequest(), - name="name_value", + client.set_inventory( + product_service.SetInventoryRequest(), + inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), + set_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_add_fulfillment_places_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.add_fulfillment_places + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_fulfillment_places + ] = mock_rpc + + request = {} + client.add_fulfillment_places(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_fulfillment_places(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_fulfillment_places_rest_required_fields( + request_type=product_service.AddFulfillmentPlacesRequest, +): + transport_class = transports.ProductServiceRestTransport + + request_init = {} + request_init["product"] = "" + request_init["type_"] = "" + request_init["place_ids"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_fulfillment_places._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["product"] = "product_value" + jsonified_request["type"] = "type__value" + jsonified_request["placeIds"] = "place_ids_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_fulfillment_places._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "product" in jsonified_request + assert jsonified_request["product"] == "product_value" + assert "type" in jsonified_request + assert jsonified_request["type"] == "type__value" + assert "placeIds" in jsonified_request + assert jsonified_request["placeIds"] == "place_ids_value" -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeProductsRequest, - dict, - ], -) -def test_purge_products_rest(request_type): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.add_fulfillment_places(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_fulfillment_places_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_fulfillment_places._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "product", + "type", + "placeIds", + ) + ) + ) + + +def test_add_fulfillment_places_rest_flattened(): + client = ProductServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + # get arguments that satisfy an http rule for this method + sample_request = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + product="product_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.purge_products(request) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + client.add_fulfillment_places(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces" + % client.transport._host, + args[1], + ) -def test_purge_products_rest_use_cached_wrapped_rpc(): +def test_add_fulfillment_places_rest_flattened_error(transport: str = "rest"): + client = ProductServiceClient( + 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.add_fulfillment_places( + product_service.AddFulfillmentPlacesRequest(), + product="product_value", + ) + + +def test_remove_fulfillment_places_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8347,17 +7475,22 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.purge_products in client._transport._wrapped_methods + assert ( + client._transport.remove_fulfillment_places + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.purge_products] = mock_rpc + client._transport._wrapped_methods[ + client._transport.remove_fulfillment_places + ] = mock_rpc request = {} - client.purge_products(request) + client.remove_fulfillment_places(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8366,21 +7499,22 @@ def test_purge_products_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.purge_products(request) + client.remove_fulfillment_places(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_purge_products_rest_required_fields( - request_type=purge_config.PurgeProductsRequest, +def test_remove_fulfillment_places_rest_required_fields( + request_type=product_service.RemoveFulfillmentPlacesRequest, ): transport_class = transports.ProductServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" + request_init["product"] = "" + request_init["type_"] = "" + request_init["place_ids"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8391,24 +7525,27 @@ def test_purge_products_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + ).remove_fulfillment_places._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" - jsonified_request["filter"] = "filter_value" + jsonified_request["product"] = "product_value" + jsonified_request["type"] = "type__value" + jsonified_request["placeIds"] = "place_ids_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).purge_products._get_unset_required_fields(jsonified_request) + ).remove_fulfillment_places._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" - assert "filter" in jsonified_request - assert jsonified_request["filter"] == "filter_value" + assert "product" in jsonified_request + assert jsonified_request["product"] == "product_value" + assert "type" in jsonified_request + assert jsonified_request["type"] == "type__value" + assert "placeIds" in jsonified_request + assert jsonified_request["placeIds"] == "place_ids_value" client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8442,32 +7579,2113 @@ def test_purge_products_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.purge_products(request) + response = client.remove_fulfillment_places(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_fulfillment_places_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_fulfillment_places._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "product", + "type", + "placeIds", + ) + ) + ) + + +def test_remove_fulfillment_places_rest_flattened(): + client = ProductServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + product="product_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.remove_fulfillment_places(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces" + % client.transport._host, + args[1], + ) + + +def test_remove_fulfillment_places_rest_flattened_error(transport: str = "rest"): + client = ProductServiceClient( + 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.remove_fulfillment_places( + product_service.RemoveFulfillmentPlacesRequest(), + product="product_value", + ) + + +def test_add_local_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.add_local_inventories + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_local_inventories + ] = mock_rpc + + request = {} + client.add_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_local_inventories_rest_required_fields( + request_type=product_service.AddLocalInventoriesRequest, +): + transport_class = transports.ProductServiceRestTransport + + request_init = {} + request_init["product"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["product"] = "product_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "product" in jsonified_request + assert jsonified_request["product"] == "product_value" + + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.add_local_inventories(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_add_local_inventories_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_local_inventories._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "product", + "localInventories", + ) + ) + ) + + +def test_add_local_inventories_rest_flattened(): + client = ProductServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + product="product_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.add_local_inventories(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories" + % client.transport._host, + args[1], + ) + + +def test_add_local_inventories_rest_flattened_error(transport: str = "rest"): + client = ProductServiceClient( + 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.add_local_inventories( + product_service.AddLocalInventoriesRequest(), + product="product_value", + ) + + +def test_remove_local_inventories_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.remove_local_inventories + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.remove_local_inventories + ] = mock_rpc + + request = {} + client.remove_local_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_local_inventories(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_local_inventories_rest_required_fields( + request_type=product_service.RemoveLocalInventoriesRequest, +): + transport_class = transports.ProductServiceRestTransport + + request_init = {} + request_init["product"] = "" + request_init["place_ids"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["product"] = "product_value" + jsonified_request["placeIds"] = "place_ids_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_local_inventories._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "product" in jsonified_request + assert jsonified_request["product"] == "product_value" + assert "placeIds" in jsonified_request + assert jsonified_request["placeIds"] == "place_ids_value" + + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.remove_local_inventories(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_local_inventories_rest_unset_required_fields(): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_local_inventories._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "product", + "placeIds", + ) + ) + ) + + +def test_remove_local_inventories_rest_flattened(): + client = ProductServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + product="product_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.remove_local_inventories(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories" + % client.transport._host, + args[1], + ) + + +def test_remove_local_inventories_rest_flattened_error(transport: str = "rest"): + client = ProductServiceClient( + 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.remove_local_inventories( + product_service.RemoveLocalInventoriesRequest(), + product="product_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProductServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + call.return_value = product.Product() + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + call.return_value = None + client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProductServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_service.ListProductsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + await client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_inventory_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProductServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_product_rest_bad_request( + request_type=product_service.CreateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.CreateProductRequest, + dict, + ], +) +def test_create_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.CreateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_create_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.CreateProductRequest.pb( + product_service.CreateProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value + + request = product_service.CreateProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_product.Product() + + client.create_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_product_rest_bad_request(request_type=product_service.GetProductRequest): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.GetProductRequest, + dict, + ], +) +def test_get_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_get_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.GetProductRequest.pb( + product_service.GetProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product.Product.to_json(product.Product()) + req.return_value.content = return_value + + request = product_service.GetProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product.Product() + + client.get_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_products_rest_bad_request( + request_type=product_service.ListProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.ListProductsRequest, + dict, + ], +) +def test_list_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = product_service.ListProductsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product_service.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_list_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.ListProductsRequest.pb( + product_service.ListProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product_service.ListProductsResponse.to_json( + product_service.ListProductsResponse() + ) + req.return_value.content = return_value + + request = product_service.ListProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product_service.ListProductsResponse() + + client.list_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_product_rest_bad_request( + request_type=product_service.UpdateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.UpdateProductRequest, + dict, + ], +) +def test_update_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.UpdateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_purge_products_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_product(request) - unset_fields = transport.purge_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "filter", - ) - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_products_rest_interceptors(null_interceptor): +def test_update_product_rest_interceptors(null_interceptor): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8475,21 +9693,20 @@ def test_purge_products_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_purge_products" + transports.ProductServiceRestInterceptor, "post_update_product" ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_purge_products" + transports.ProductServiceRestInterceptor, "pre_update_product" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = purge_config.PurgeProductsRequest.pb( - purge_config.PurgeProductsRequest() + pb_message = product_service.UpdateProductRequest.pb( + product_service.UpdateProductRequest() ) transcode.return_value = { "method": "post", @@ -8498,22 +9715,20 @@ def test_purge_products_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value - request = purge_config.PurgeProductsRequest() + request = product_service.UpdateProductRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = gcr_product.Product() - client.purge_products( + client.update_product( request, metadata=[ ("key", "val"), @@ -8525,206 +9740,69 @@ def test_purge_products_rest_interceptors(null_interceptor): post.assert_called_once() -def test_purge_products_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeProductsRequest +def test_delete_product_rest_bad_request( + request_type=product_service.DeleteProductRequest, ): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.purge_products(request) - - -def test_purge_products_rest_error(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportProductsRequest, - dict, - ], -) -def test_import_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_products_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_products in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.import_products] = mock_rpc - - request = {} - client.import_products(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.import_products(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_import_products_rest_required_fields( - request_type=import_config.ImportProductsRequest, -): - transport_class = transports.ProductServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).import_products._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() - ).import_products._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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + request = request_type(**request_init) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_product(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_products(request) +@pytest.mark.parametrize( + "request_type", + [ + product_service.DeleteProductRequest, + dict, + ], +) +def test_delete_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = None -def test_import_products_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_product(request) - unset_fields = transport.import_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "inputConfig", - ) - ) - ) + # Establish that the response is the type that we expect. + assert response is None @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_products_rest_interceptors(null_interceptor): +def test_delete_product_rest_interceptors(null_interceptor): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8732,21 +9810,17 @@ def test_import_products_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_import_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_import_products" + transports.ProductServiceRestInterceptor, "pre_delete_product" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportProductsRequest.pb( - import_config.ImportProductsRequest() + pb_message = product_service.DeleteProductRequest.pb( + product_service.DeleteProductRequest() ) transcode.return_value = { "method": "post", @@ -8755,22 +9829,17 @@ def test_import_products_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) - request = import_config.ImportProductsRequest() + request = product_service.DeleteProductRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - client.import_products( + client.delete_product( request, metadata=[ ("key", "val"), @@ -8779,17 +9848,14 @@ def test_import_products_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_import_products_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportProductsRequest +def test_purge_products_rest_bad_request( + request_type=purge_config.PurgeProductsRequest, ): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" @@ -8801,30 +9867,25 @@ def test_import_products_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.import_products(request) - - -def test_import_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.purge_products(request) @pytest.mark.parametrize( "request_type", [ - export_config.ExportProductsRequest, + purge_config.PurgeProductsRequest, dict, ], ) -def test_export_products_rest(request_type): +def test_purge_products_rest_call_success(request_type): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -8839,149 +9900,138 @@ def test_export_products_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.export_products(request) + response = client.purge_products(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_products_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + json_return_value = json_format.MessageToJson(return_value) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.export_products in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_purge_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_purge_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeProductsRequest.pb( + purge_config.PurgeProductsRequest() ) - client._transport._wrapped_methods[client._transport.export_products] = mock_rpc - - request = {} - client.export_products(request) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = purge_config.PurgeProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.export_products(request) + client.purge_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_export_products_rest_required_fields( - request_type=export_config.ExportProductsRequest, +def test_import_products_rest_bad_request( + request_type=import_config.ImportProductsRequest, ): - transport_class = transports.ProductServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).export_products._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() - ).export_products._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 = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_products(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_products(request) +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportProductsRequest, + dict, + ], +) +def test_import_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") -def test_export_products_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_products(request) - unset_fields = transport.export_products._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "outputConfig", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_products_rest_interceptors(null_interceptor): +def test_import_products_rest_interceptors(null_interceptor): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8989,6 +10039,7 @@ def test_export_products_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -8996,14 +10047,14 @@ def test_export_products_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_export_products" + transports.ProductServiceRestInterceptor, "post_import_products" ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_export_products" + transports.ProductServiceRestInterceptor, "pre_import_products" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = export_config.ExportProductsRequest.pb( - export_config.ExportProductsRequest() + pb_message = import_config.ImportProductsRequest.pb( + import_config.ImportProductsRequest() ) transcode.return_value = { "method": "post", @@ -9012,14 +10063,12 @@ def test_export_products_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = export_config.ExportProductsRequest() + request = import_config.ImportProductsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9027,7 +10076,7 @@ def test_export_products_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.export_products( + client.import_products( request, metadata=[ ("key", "val"), @@ -9040,13 +10089,11 @@ def test_export_products_rest_interceptors(null_interceptor): def test_export_products_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportProductsRequest + request_type=export_config.ExportProductsRequest, ): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" @@ -9058,37 +10105,30 @@ def test_export_products_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.export_products(request) -def test_export_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - product_service.SetInventoryRequest, + export_config.ExportProductsRequest, dict, ], ) -def test_set_inventory_rest(request_type): +def test_export_products_rest_call_success(request_type): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" } request = request_type(**request_init) @@ -9098,132 +10138,138 @@ def test_set_inventory_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_inventory(request) + response = client.export_products(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + json_return_value = json_format.MessageToJson(return_value) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.set_inventory in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_export_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_export_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportProductsRequest.pb( + export_config.ExportProductsRequest() ) - client._transport._wrapped_methods[client._transport.set_inventory] = mock_rpc - - request = {} - client.set_inventory(request) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = export_config.ExportProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.set_inventory(request) + client.export_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_set_inventory_rest_required_fields( +def test_set_inventory_rest_bad_request( request_type=product_service.SetInventoryRequest, ): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).set_inventory._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() - ).set_inventory._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_inventory(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_inventory(request) +@pytest.mark.parametrize( + "request_type", + [ + product_service.SetInventoryRequest, + dict, + ], +) +def test_set_inventory_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = operations_pb2.Operation(name="operations/spam") -def test_set_inventory_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_inventory(request) - unset_fields = transport.set_inventory._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("inventory",))) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9235,6 +10281,7 @@ def test_set_inventory_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9258,12 +10305,10 @@ def test_set_inventory_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = product_service.SetInventoryRequest() metadata = [ @@ -9285,19 +10330,15 @@ def test_set_inventory_rest_interceptors(null_interceptor): post.assert_called_once() -def test_set_inventory_rest_bad_request( - transport: str = "rest", request_type=product_service.SetInventoryRequest +def test_add_fulfillment_places_rest_bad_request( + request_type=product_service.AddFulfillmentPlacesRequest, ): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" } request = request_type(**request_init) @@ -9306,78 +10347,13 @@ def test_set_inventory_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_inventory(request) - - -def test_set_inventory_rest_flattened(): - client = ProductServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - - # get truthy value for each flattened field - mock_args = dict( - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.set_inventory(**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/v2alpha/{inventory.name=projects/*/locations/*/catalogs/*/branches/*/products/**}:setInventory" - % client.transport._host, - args[1], - ) - - -def test_set_inventory_rest_flattened_error(transport: str = "rest"): - client = ProductServiceClient( - 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.set_inventory( - product_service.SetInventoryRequest(), - inventory=product.Product(expire_time=timestamp_pb2.Timestamp(seconds=751)), - set_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_set_inventory_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.add_fulfillment_places(request) @pytest.mark.parametrize( @@ -9386,178 +10362,33 @@ def test_set_inventory_rest_error(): product_service.AddFulfillmentPlacesRequest, dict, ], -) -def test_add_fulfillment_places_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_add_fulfillment_places_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.add_fulfillment_places - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.add_fulfillment_places - ] = mock_rpc - - request = {} - client.add_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.add_fulfillment_places(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_add_fulfillment_places_rest_required_fields( - request_type=product_service.AddFulfillmentPlacesRequest, -): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request_init["product"] = "" - request_init["type_"] = "" - request_init["place_ids"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_fulfillment_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["product"] = "product_value" - jsonified_request["type"] = "type__value" - jsonified_request["placeIds"] = "place_ids_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_fulfillment_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" - assert "type" in jsonified_request - assert jsonified_request["type"] == "type__value" - assert "placeIds" in jsonified_request - assert jsonified_request["placeIds"] == "place_ids_value" - - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.add_fulfillment_places(request) +) +def test_add_fulfillment_places_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") -def test_add_fulfillment_places_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_fulfillment_places(request) - unset_fields = transport.add_fulfillment_places._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "product", - "type", - "placeIds", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9569,6 +10400,7 @@ def test_add_fulfillment_places_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9592,12 +10424,10 @@ def test_add_fulfillment_places_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = product_service.AddFulfillmentPlacesRequest() metadata = [ @@ -9619,14 +10449,12 @@ def test_add_fulfillment_places_rest_interceptors(null_interceptor): post.assert_called_once() -def test_add_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.AddFulfillmentPlacesRequest +def test_remove_fulfillment_places_rest_bad_request( + request_type=product_service.RemoveFulfillmentPlacesRequest, ): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" @@ -9638,74 +10466,13 @@ def test_add_fulfillment_places_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.add_fulfillment_places(request) - - -def test_add_fulfillment_places_rest_flattened(): - client = ProductServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - - # get truthy value for each flattened field - mock_args = dict( - product="product_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.add_fulfillment_places(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addFulfillmentPlaces" - % client.transport._host, - args[1], - ) - - -def test_add_fulfillment_places_rest_flattened_error(transport: str = "rest"): - client = ProductServiceClient( - 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.add_fulfillment_places( - product_service.AddFulfillmentPlacesRequest(), - product="product_value", - ) - - -def test_add_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.remove_fulfillment_places(request) @pytest.mark.parametrize( @@ -9715,10 +10482,9 @@ def test_add_fulfillment_places_rest_error(): dict, ], ) -def test_remove_fulfillment_places_rest(request_type): +def test_remove_fulfillment_places_rest_call_success(request_type): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9733,159 +10499,15 @@ def test_remove_fulfillment_places_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_remove_fulfillment_places_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.remove_fulfillment_places - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_fulfillment_places - ] = mock_rpc - - request = {} - client.remove_fulfillment_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.remove_fulfillment_places(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_remove_fulfillment_places_rest_required_fields( - request_type=product_service.RemoveFulfillmentPlacesRequest, -): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request_init["product"] = "" - request_init["type_"] = "" - request_init["place_ids"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_fulfillment_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["product"] = "product_value" - jsonified_request["type"] = "type__value" - jsonified_request["placeIds"] = "place_ids_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_fulfillment_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" - assert "type" in jsonified_request - assert jsonified_request["type"] == "type__value" - assert "placeIds" in jsonified_request - assert jsonified_request["placeIds"] == "place_ids_value" - - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.remove_fulfillment_places(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_remove_fulfillment_places_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_fulfillment_places(request) - unset_fields = transport.remove_fulfillment_places._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "product", - "type", - "placeIds", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9897,6 +10519,7 @@ def test_remove_fulfillment_places_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9920,12 +10543,10 @@ def test_remove_fulfillment_places_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = product_service.RemoveFulfillmentPlacesRequest() metadata = [ @@ -9947,14 +10568,12 @@ def test_remove_fulfillment_places_rest_interceptors(null_interceptor): post.assert_called_once() -def test_remove_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveFulfillmentPlacesRequest +def test_add_local_inventories_rest_bad_request( + request_type=product_service.AddLocalInventoriesRequest, ): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" @@ -9966,74 +10585,13 @@ def test_remove_fulfillment_places_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.remove_fulfillment_places(request) - - -def test_remove_fulfillment_places_rest_flattened(): - client = ProductServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - - # get truthy value for each flattened field - mock_args = dict( - product="product_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.remove_fulfillment_places(**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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeFulfillmentPlaces" - % client.transport._host, - args[1], - ) - - -def test_remove_fulfillment_places_rest_flattened_error(transport: str = "rest"): - client = ProductServiceClient( - 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.remove_fulfillment_places( - product_service.RemoveFulfillmentPlacesRequest(), - product="product_value", - ) - - -def test_remove_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.add_local_inventories(request) @pytest.mark.parametrize( @@ -10043,10 +10601,9 @@ def test_remove_fulfillment_places_rest_error(): dict, ], ) -def test_add_local_inventories_rest(request_type): +def test_add_local_inventories_rest_call_success(request_type): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -10061,154 +10618,138 @@ def test_add_local_inventories_rest(request_type): return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.add_local_inventories(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_add_local_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + json_return_value = json_format.MessageToJson(return_value) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.add_local_inventories - in client._transport._wrapped_methods - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_local_inventories_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_add_local_inventories" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_add_local_inventories" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.AddLocalInventoriesRequest.pb( + product_service.AddLocalInventoriesRequest() ) - client._transport._wrapped_methods[ - client._transport.add_local_inventories - ] = mock_rpc - - request = {} - client.add_local_inventories(request) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() + request = product_service.AddLocalInventoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - client.add_local_inventories(request) + client.add_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_add_local_inventories_rest_required_fields( - request_type=product_service.AddLocalInventoriesRequest, +def test_remove_local_inventories_rest_bad_request( + request_type=product_service.RemoveLocalInventoriesRequest, ): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request_init["product"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["product"] = "product_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_local_inventories(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_local_inventories(request) +@pytest.mark.parametrize( + "request_type", + [ + product_service.RemoveLocalInventoriesRequest, + dict, + ], +) +def test_remove_local_inventories_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") -def test_add_local_inventories_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_local_inventories(request) - unset_fields = transport.add_local_inventories._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "product", - "localInventories", - ) - ) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_local_inventories_rest_interceptors(null_interceptor): +def test_remove_local_inventories_rest_interceptors(null_interceptor): transport = transports.ProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10216,6 +10757,7 @@ def test_add_local_inventories_rest_interceptors(null_interceptor): else transports.ProductServiceRestInterceptor(), ) client = ProductServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -10223,14 +10765,14 @@ def test_add_local_inventories_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_add_local_inventories" + transports.ProductServiceRestInterceptor, "post_remove_local_inventories" ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_add_local_inventories" + transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = product_service.AddLocalInventoriesRequest.pb( - product_service.AddLocalInventoriesRequest() + pb_message = product_service.RemoveLocalInventoriesRequest.pb( + product_service.RemoveLocalInventoriesRequest() ) transcode.return_value = { "method": "post", @@ -10239,14 +10781,12 @@ def test_add_local_inventories_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - request = product_service.AddLocalInventoriesRequest() + request = product_service.RemoveLocalInventoriesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10254,7 +10794,7 @@ def test_add_local_inventories_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.add_local_inventories( + client.remove_local_inventories( request, metadata=[ ("key", "val"), @@ -10266,19 +10806,20 @@ def test_add_local_inventories_rest_interceptors(null_interceptor): post.assert_called_once() -def test_add_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.AddLocalInventoriesRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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( @@ -10286,502 +10827,400 @@ def test_add_local_inventories_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.add_local_inventories(request) + client.get_operation(request) -def test_add_local_inventories_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + 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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - - # get truthy value for each flattened field - mock_args = dict( - product="product_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.add_local_inventories(**mock_args) + response = client.get_operation(request) - # 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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:addLocalInventories" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_add_local_inventories_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.add_local_inventories( - product_service.AddLocalInventoriesRequest(), - product="product_value", - ) - - -def test_add_local_inventories_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + @pytest.mark.parametrize( "request_type", [ - product_service.RemoveLocalInventoriesRequest, + operations_pb2.ListOperationsRequest, dict, ], ) -def test_remove_local_inventories_rest(request_type): +def test_list_operations_rest(request_type): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } + request_init = {"name": "projects/sample1/locations/sample2/catalogs/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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = operations_pb2.ListOperationsResponse() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_local_inventories(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_remove_local_inventories_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.remove_local_inventories - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.remove_local_inventories - ] = mock_rpc - - request = {} - client.remove_local_inventories(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.remove_local_inventories(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + response = client.list_operations(request) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_remove_local_inventories_rest_required_fields( - request_type=product_service.RemoveLocalInventoriesRequest, -): - transport_class = transports.ProductServiceRestTransport - request_init = {} - request_init["product"] = "" - request_init["place_ids"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_initialize_client_w_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["product"] = "product_value" - jsonified_request["placeIds"] = "place_ids_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_local_inventories._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "product" in jsonified_request - assert jsonified_request["product"] == "product_value" - assert "placeIds" in jsonified_request - assert jsonified_request["placeIds"] == "place_ids_value" +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_rest(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + client.create_product(request=None) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + assert args[0] == request_msg - response = client.remove_local_inventories(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + client.get_product(request=None) -def test_remove_local_inventories_rest_unset_required_fields(): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() - unset_fields = transport.remove_local_inventories._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "product", - "placeIds", - ) - ) - ) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_local_inventories_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), + transport="rest", ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_remove_local_inventories" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.RemoveLocalInventoriesRequest.pb( - product_service.RemoveLocalInventoriesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - request = product_service.RemoveLocalInventoriesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + client.list_products(request=None) - client.remove_local_inventories( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() - pre.assert_called_once() - post.assert_called_once() + assert args[0] == request_msg -def test_remove_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveLocalInventoriesRequest -): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_rest(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + client.update_product(request=None) - # 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.remove_local_inventories(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + assert args[0] == request_msg -def test_remove_local_inventories_rest_flattened(): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_rest(): client = ProductServiceClient( 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + client.delete_product(request=None) - # get arguments that satisfy an http rule for this method - sample_request = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() - # get truthy value for each flattened field - mock_args = dict( - product="product_value", - ) - mock_args.update(sample_request) + assert args[0] == request_msg - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - client.remove_local_inventories(**mock_args) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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/v2alpha/{product=projects/*/locations/*/catalogs/*/branches/*/products/**}:removeLocalInventories" - % client.transport._host, - args[1], - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + assert args[0] == request_msg -def test_remove_local_inventories_rest_flattened_error(transport: str = "rest"): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_rest(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_local_inventories( - product_service.RemoveLocalInventoriesRequest(), - product="product_value", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg -def test_remove_local_inventories_rest_error(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_products_empty_call_rest(): client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + client.export_products(request=None) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProductServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProductServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ProductServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + client.add_local_inventories(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.ProductServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + client.remove_local_inventories(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProductServiceClient.get_transport_class(transport_name)( + +def test_product_service_rest_lro_client(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -11032,23 +11471,6 @@ def test_product_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_product_service_rest_lro_client(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -11502,141 +11924,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11664,7 +11951,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11719,7 +12006,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11766,7 +12053,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -11809,7 +12096,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11864,7 +12151,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11911,7 +12198,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -11927,22 +12214,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_project_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_project_service.py index 5d8988c08c6f..19e52c133fc5 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_project_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_project_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,14 +63,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2alpha.services.project_service import ( ProjectServiceAsyncClient, @@ -66,10 +75,24 @@ from google.cloud.retail_v2alpha.types import project_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1171,25 +1194,6 @@ def test_get_project(request_type, transport: str = "grpc"): ] -def test_get_project_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_project), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetProjectRequest() - - def test_get_project_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1253,30 +1257,6 @@ def test_get_project_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_project_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_project), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.Project( - name="name_value", - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.get_project() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetProjectRequest() - - @pytest.mark.asyncio async def test_get_project_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1285,7 +1265,7 @@ async def test_get_project_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1324,7 +1304,7 @@ async def test_get_project_async( transport: str = "grpc_asyncio", request_type=project_service.GetProjectRequest ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1394,7 +1374,7 @@ def test_get_project_field_headers(): @pytest.mark.asyncio async def test_get_project_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,7 +1442,7 @@ def test_get_project_flattened_error(): @pytest.mark.asyncio async def test_get_project_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1489,7 +1469,7 @@ async def test_get_project_flattened_async(): @pytest.mark.asyncio async def test_get_project_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1541,25 +1521,6 @@ def test_accept_terms(request_type, transport: str = "grpc"): ] -def test_accept_terms_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.accept_terms), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.accept_terms() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.AcceptTermsRequest() - - def test_accept_terms_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1623,30 +1584,6 @@ def test_accept_terms_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_accept_terms_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.accept_terms), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_project.Project( - name="name_value", - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.accept_terms() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.AcceptTermsRequest() - - @pytest.mark.asyncio async def test_accept_terms_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1655,7 +1592,7 @@ async def test_accept_terms_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1694,7 +1631,7 @@ async def test_accept_terms_async( transport: str = "grpc_asyncio", request_type=project_service.AcceptTermsRequest ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1764,7 +1701,7 @@ def test_accept_terms_field_headers(): @pytest.mark.asyncio async def test_accept_terms_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1832,7 +1769,7 @@ def test_accept_terms_flattened_error(): @pytest.mark.asyncio async def test_accept_terms_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1859,7 +1796,7 @@ async def test_accept_terms_flattened_async(): @pytest.mark.asyncio async def test_accept_terms_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1904,25 +1841,6 @@ def test_enroll_solution(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_enroll_solution_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_solution), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.enroll_solution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.EnrollSolutionRequest() - - def test_enroll_solution_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1991,27 +1909,6 @@ def test_enroll_solution_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_enroll_solution_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.enroll_solution), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.enroll_solution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.EnrollSolutionRequest() - - @pytest.mark.asyncio async def test_enroll_solution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2020,7 +1917,7 @@ async def test_enroll_solution_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2064,7 +1961,7 @@ async def test_enroll_solution_async( transport: str = "grpc_asyncio", request_type=project_service.EnrollSolutionRequest ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2127,7 +2024,7 @@ def test_enroll_solution_field_headers(): @pytest.mark.asyncio async def test_enroll_solution_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2196,27 +2093,6 @@ def test_list_enrolled_solutions(request_type, transport: str = "grpc"): ] -def test_list_enrolled_solutions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrolled_solutions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_enrolled_solutions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.ListEnrolledSolutionsRequest() - - def test_list_enrolled_solutions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2287,31 +2163,6 @@ def test_list_enrolled_solutions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_enrolled_solutions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_enrolled_solutions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project_service.ListEnrolledSolutionsResponse( - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.list_enrolled_solutions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.ListEnrolledSolutionsRequest() - - @pytest.mark.asyncio async def test_list_enrolled_solutions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2320,7 +2171,7 @@ async def test_list_enrolled_solutions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2360,7 +2211,7 @@ async def test_list_enrolled_solutions_async( request_type=project_service.ListEnrolledSolutionsRequest, ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2432,7 +2283,7 @@ def test_list_enrolled_solutions_field_headers(): @pytest.mark.asyncio async def test_list_enrolled_solutions_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2506,7 +2357,7 @@ def test_list_enrolled_solutions_flattened_error(): @pytest.mark.asyncio async def test_list_enrolled_solutions_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2537,7 +2388,7 @@ async def test_list_enrolled_solutions_flattened_async(): @pytest.mark.asyncio async def test_list_enrolled_solutions_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2587,27 +2438,6 @@ def test_get_logging_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_logging_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_logging_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_logging_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetLoggingConfigRequest() - - def test_get_logging_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2677,31 +2507,6 @@ def test_get_logging_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_logging_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_logging_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.LoggingConfig( - name="name_value", - ) - ) - response = await client.get_logging_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetLoggingConfigRequest() - - @pytest.mark.asyncio async def test_get_logging_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2710,7 +2515,7 @@ async def test_get_logging_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2750,7 +2555,7 @@ async def test_get_logging_config_async( request_type=project_service.GetLoggingConfigRequest, ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2820,7 +2625,7 @@ def test_get_logging_config_field_headers(): @pytest.mark.asyncio async def test_get_logging_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2894,7 +2699,7 @@ def test_get_logging_config_flattened_error(): @pytest.mark.asyncio async def test_get_logging_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2925,7 +2730,7 @@ async def test_get_logging_config_flattened_async(): @pytest.mark.asyncio async def test_get_logging_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2975,27 +2780,6 @@ def test_update_logging_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_update_logging_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_logging_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_logging_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateLoggingConfigRequest() - - def test_update_logging_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3062,31 +2846,6 @@ def test_update_logging_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_logging_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_logging_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.LoggingConfig( - name="name_value", - ) - ) - response = await client.update_logging_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateLoggingConfigRequest() - - @pytest.mark.asyncio async def test_update_logging_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3095,7 +2854,7 @@ async def test_update_logging_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3135,7 +2894,7 @@ async def test_update_logging_config_async( request_type=project_service.UpdateLoggingConfigRequest, ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3205,7 +2964,7 @@ def test_update_logging_config_field_headers(): @pytest.mark.asyncio async def test_update_logging_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3284,7 +3043,7 @@ def test_update_logging_config_flattened_error(): @pytest.mark.asyncio async def test_update_logging_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3319,7 +3078,7 @@ async def test_update_logging_config_flattened_async(): @pytest.mark.asyncio async def test_update_logging_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3368,25 +3127,6 @@ def test_get_alert_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_alert_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetAlertConfigRequest() - - def test_get_alert_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3452,29 +3192,6 @@ def test_get_alert_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_alert_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.AlertConfig( - name="name_value", - ) - ) - response = await client.get_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetAlertConfigRequest() - - @pytest.mark.asyncio async def test_get_alert_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3483,7 +3200,7 @@ async def test_get_alert_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3522,7 +3239,7 @@ async def test_get_alert_config_async( transport: str = "grpc_asyncio", request_type=project_service.GetAlertConfigRequest ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3588,7 +3305,7 @@ def test_get_alert_config_field_headers(): @pytest.mark.asyncio async def test_get_alert_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3656,7 +3373,7 @@ def test_get_alert_config_flattened_error(): @pytest.mark.asyncio async def test_get_alert_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3683,7 +3400,7 @@ async def test_get_alert_config_flattened_async(): @pytest.mark.asyncio async def test_get_alert_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3733,27 +3450,6 @@ def test_update_alert_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_update_alert_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_alert_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateAlertConfigRequest() - - def test_update_alert_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3819,31 +3515,6 @@ def test_update_alert_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_alert_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_alert_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.AlertConfig( - name="name_value", - ) - ) - response = await client.update_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateAlertConfigRequest() - - @pytest.mark.asyncio async def test_update_alert_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3852,7 +3523,7 @@ async def test_update_alert_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3892,7 +3563,7 @@ async def test_update_alert_config_async( request_type=project_service.UpdateAlertConfigRequest, ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3962,7 +3633,7 @@ def test_update_alert_config_field_headers(): @pytest.mark.asyncio async def test_update_alert_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4039,7 +3710,7 @@ def test_update_alert_config_flattened_error(): @pytest.mark.asyncio async def test_update_alert_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4072,7 +3743,7 @@ async def test_update_alert_config_flattened_async(): @pytest.mark.asyncio async def test_update_alert_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4085,50 +3756,6 @@ async def test_update_alert_config_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - project_service.GetProjectRequest, - dict, - ], -) -def test_get_project_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/retailProject"} - 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 = project.Project( - name="name_value", - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.Project.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_project(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.Project) - assert response.name == "name_value" - assert response.enrolled_solutions == [ - common.SolutionType.SOLUTION_TYPE_RECOMMENDATION - ] - - def test_get_project_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4248,85 +3875,6 @@ def test_get_project_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_project_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_project" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_get_project" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.GetProjectRequest.pb( - project_service.GetProjectRequest() - ) - 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 = project.Project.to_json(project.Project()) - - request = project_service.GetProjectRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.Project() - - client.get_project( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_project_rest_bad_request( - transport: str = "rest", request_type=project_service.GetProjectRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/retailProject"} - 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_project(request) - - def test_get_project_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4383,56 +3931,6 @@ def test_get_project_rest_flattened_error(transport: str = "rest"): ) -def test_get_project_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.AcceptTermsRequest, - dict, - ], -) -def test_accept_terms_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"project": "projects/sample1/retailProject"} - 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 = gcr_project.Project( - name="name_value", - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_project.Project.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.accept_terms(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_project.Project) - assert response.name == "name_value" - assert response.enrolled_solutions == [ - common.SolutionType.SOLUTION_TYPE_RECOMMENDATION - ] - - def test_accept_terms_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4553,87 +4051,8 @@ def test_accept_terms_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("project",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_accept_terms_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_accept_terms" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_accept_terms" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.AcceptTermsRequest.pb( - project_service.AcceptTermsRequest() - ) - 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 = gcr_project.Project.to_json(gcr_project.Project()) - - request = project_service.AcceptTermsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_project.Project() - - client.accept_terms( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_accept_terms_rest_bad_request( - transport: str = "rest", request_type=project_service.AcceptTermsRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"project": "projects/sample1/retailProject"} - 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.accept_terms(request) - - -def test_accept_terms_rest_flattened(): - client = ProjectServiceClient( +def test_accept_terms_rest_flattened(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -4689,47 +4108,6 @@ def test_accept_terms_rest_flattened_error(transport: str = "rest"): ) -def test_accept_terms_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.EnrollSolutionRequest, - dict, - ], -) -def test_enroll_solution_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"project": "projects/sample1"} - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.enroll_solution(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_enroll_solution_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4859,137 +4237,6 @@ def test_enroll_solution_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enroll_solution_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProjectServiceRestInterceptor, "post_enroll_solution" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_enroll_solution" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.EnrollSolutionRequest.pb( - project_service.EnrollSolutionRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = project_service.EnrollSolutionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.enroll_solution( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_enroll_solution_rest_bad_request( - transport: str = "rest", request_type=project_service.EnrollSolutionRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"project": "projects/sample1"} - 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.enroll_solution(request) - - -def test_enroll_solution_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.ListEnrolledSolutionsRequest, - dict, - ], -) -def test_list_enrolled_solutions_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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 = project_service.ListEnrolledSolutionsResponse( - enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project_service.ListEnrolledSolutionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_enrolled_solutions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project_service.ListEnrolledSolutionsResponse) - assert response.enrolled_solutions == [ - common.SolutionType.SOLUTION_TYPE_RECOMMENDATION - ] - - def test_list_enrolled_solutions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5116,93 +4363,10 @@ def test_list_enrolled_solutions_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_enrolled_solutions_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( +def test_list_enrolled_solutions_rest_flattened(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_list_enrolled_solutions" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_list_enrolled_solutions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.ListEnrolledSolutionsRequest.pb( - project_service.ListEnrolledSolutionsRequest() - ) - 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 = ( - project_service.ListEnrolledSolutionsResponse.to_json( - project_service.ListEnrolledSolutionsResponse() - ) - ) - - request = project_service.ListEnrolledSolutionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project_service.ListEnrolledSolutionsResponse() - - client.list_enrolled_solutions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_enrolled_solutions_rest_bad_request( - transport: str = "rest", request_type=project_service.ListEnrolledSolutionsRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - 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.list_enrolled_solutions(request) - - -def test_list_enrolled_solutions_rest_flattened(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5255,52 +4419,6 @@ def test_list_enrolled_solutions_rest_flattened_error(transport: str = "rest"): ) -def test_list_enrolled_solutions_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.GetLoggingConfigRequest, - dict, - ], -) -def test_get_logging_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/loggingConfig"} - 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 = project.LoggingConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.LoggingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_logging_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.LoggingConfig) - assert response.name == "name_value" - - def test_get_logging_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5424,87 +4542,6 @@ def test_get_logging_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_logging_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_logging_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_get_logging_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.GetLoggingConfigRequest.pb( - project_service.GetLoggingConfigRequest() - ) - 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 = project.LoggingConfig.to_json( - project.LoggingConfig() - ) - - request = project_service.GetLoggingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.LoggingConfig() - - client.get_logging_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_logging_config_rest_bad_request( - transport: str = "rest", request_type=project_service.GetLoggingConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/loggingConfig"} - 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_logging_config(request) - - def test_get_logging_config_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5561,166 +4598,41 @@ def test_get_logging_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_logging_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_logging_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - project_service.UpdateLoggingConfigRequest, - dict, - ], -) -def test_update_logging_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Ensure method has been cached + assert ( + client._transport.update_logging_config + in client._transport._wrapped_methods + ) - # send a request that will satisfy transcoding - request_init = {"logging_config": {"name": "projects/sample1/loggingConfig"}} - request_init["logging_config"] = { - "name": "projects/sample1/loggingConfig", - "default_log_generation_rule": { - "logging_level": 1, - "info_log_sample_rate": 0.21050000000000002, - }, - "service_log_generation_rules": [ - {"service_name": "service_name_value", "log_generation_rule": {}} - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_logging_config + ] = mock_rpc - # Determine if the message type is proto-plus or protobuf - test_field = project_service.UpdateLoggingConfigRequest.meta.fields[ - "logging_config" - ] + request = {} + client.update_logging_config(request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["logging_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["logging_config"][field])): - del request_init["logging_config"][field][i][subfield] - else: - del request_init["logging_config"][field][subfield] - 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 = project.LoggingConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.LoggingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_logging_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.LoggingConfig) - assert response.name == "name_value" - - -def test_update_logging_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_logging_config - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.update_logging_config - ] = mock_rpc - - request = {} - client.update_logging_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_logging_config(request) + client.update_logging_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5808,87 +4720,6 @@ def test_update_logging_config_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("loggingConfig",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_logging_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_logging_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_update_logging_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.UpdateLoggingConfigRequest.pb( - project_service.UpdateLoggingConfigRequest() - ) - 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 = project.LoggingConfig.to_json( - project.LoggingConfig() - ) - - request = project_service.UpdateLoggingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.LoggingConfig() - - client.update_logging_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_logging_config_rest_bad_request( - transport: str = "rest", request_type=project_service.UpdateLoggingConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"logging_config": {"name": "projects/sample1/loggingConfig"}} - 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_logging_config(request) - - def test_update_logging_config_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5948,52 +4779,6 @@ def test_update_logging_config_rest_flattened_error(transport: str = "rest"): ) -def test_update_logging_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.GetAlertConfigRequest, - dict, - ], -) -def test_get_alert_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/alertConfig"} - 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 = project.AlertConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.AlertConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_alert_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.AlertConfig) - assert response.name == "name_value" - - def test_get_alert_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6115,89 +4900,10 @@ def test_get_alert_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_alert_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( +def test_get_alert_config_rest_flattened(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_alert_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_get_alert_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.GetAlertConfigRequest.pb( - project_service.GetAlertConfigRequest() - ) - 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 = project.AlertConfig.to_json(project.AlertConfig()) - - request = project_service.GetAlertConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.AlertConfig() - - client.get_alert_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_alert_config_rest_bad_request( - transport: str = "rest", request_type=project_service.GetAlertConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/alertConfig"} - 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_alert_config(request) - - -def test_get_alert_config_rest_flattened(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -6249,129 +4955,6 @@ def test_get_alert_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_alert_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - project_service.UpdateAlertConfigRequest, - dict, - ], -) -def test_update_alert_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} - request_init["alert_config"] = { - "name": "projects/sample1/alertConfig", - "alert_policies": [ - { - "alert_group": "alert_group_value", - "enroll_status": 1, - "recipients": [{"email_address": "email_address_value"}], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = project_service.UpdateAlertConfigRequest.meta.fields["alert_config"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["alert_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["alert_config"][field])): - del request_init["alert_config"][field][i][subfield] - else: - del request_init["alert_config"][field][subfield] - 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 = project.AlertConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.AlertConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_alert_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.AlertConfig) - assert response.name == "name_value" - - def test_update_alert_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6493,85 +5076,6 @@ def test_update_alert_config_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("alertConfig",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_alert_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_alert_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_update_alert_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.UpdateAlertConfigRequest.pb( - project_service.UpdateAlertConfigRequest() - ) - 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 = project.AlertConfig.to_json(project.AlertConfig()) - - request = project_service.UpdateAlertConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.AlertConfig() - - client.update_alert_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_alert_config_rest_bad_request( - transport: str = "rest", request_type=project_service.UpdateAlertConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} - 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_alert_config(request) - - def test_update_alert_config_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6631,12 +5135,6 @@ def test_update_alert_config_rest_flattened_error(transport: str = "rest"): ) -def test_update_alert_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProjectServiceGrpcTransport( @@ -6678,69 +5176,1919 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.ProjectServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProjectServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProjectServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectServiceGrpcTransport, + transports.ProjectServiceGrpcAsyncIOTransport, + transports.ProjectServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProjectServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_project_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + call.return_value = project.Project() + client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_accept_terms_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.accept_terms), "__call__") as call: + call.return_value = gcr_project.Project() + client.accept_terms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.AcceptTermsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enroll_solution_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.enroll_solution), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.enroll_solution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.EnrollSolutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_enrolled_solutions_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrolled_solutions), "__call__" + ) as call: + call.return_value = project_service.ListEnrolledSolutionsResponse() + client.list_enrolled_solutions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.ListEnrolledSolutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_logging_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_logging_config), "__call__" + ) as call: + call.return_value = project.LoggingConfig() + client.get_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetLoggingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_logging_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logging_config), "__call__" + ) as call: + call.return_value = project.LoggingConfig() + client.update_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateLoggingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_alert_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + call.return_value = project.AlertConfig() + client.get_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_alert_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + call.return_value = project.AlertConfig() + client.update_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProjectServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_project_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.Project( + name="name_value", + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_accept_terms_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.accept_terms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_project.Project( + name="name_value", + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.accept_terms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.AcceptTermsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_enroll_solution_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.enroll_solution), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.enroll_solution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.EnrollSolutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_enrolled_solutions_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrolled_solutions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project_service.ListEnrolledSolutionsResponse( + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.list_enrolled_solutions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.ListEnrolledSolutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_logging_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_logging_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.LoggingConfig( + name="name_value", + ) + ) + await client.get_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetLoggingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_logging_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logging_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.LoggingConfig( + name="name_value", + ) + ) + await client.update_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateLoggingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_alert_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.AlertConfig( + name="name_value", + ) + ) + await client.get_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_alert_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.AlertConfig( + name="name_value", + ) + ) + await client.update_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProjectServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_project_rest_bad_request(request_type=project_service.GetProjectRequest): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/retailProject"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_project(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.GetProjectRequest, + dict, + ], +) +def test_get_project_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/retailProject"} + 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 = project.Project( + name="name_value", + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.Project.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_project(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.Project) + assert response.name == "name_value" + assert response.enrolled_solutions == [ + common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_project" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_get_project" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.GetProjectRequest.pb( + project_service.GetProjectRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.Project.to_json(project.Project()) + req.return_value.content = return_value + + request = project_service.GetProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.Project() + + client.get_project( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_accept_terms_rest_bad_request(request_type=project_service.AcceptTermsRequest): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "projects/sample1/retailProject"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.accept_terms(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.AcceptTermsRequest, + dict, + ], +) +def test_accept_terms_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "projects/sample1/retailProject"} + 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 = gcr_project.Project( + name="name_value", + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_project.Project.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.accept_terms(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_project.Project) + assert response.name == "name_value" + assert response.enrolled_solutions == [ + common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_accept_terms_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_accept_terms" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_accept_terms" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.AcceptTermsRequest.pb( + project_service.AcceptTermsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_project.Project.to_json(gcr_project.Project()) + req.return_value.content = return_value + + request = project_service.AcceptTermsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_project.Project() + + client.accept_terms( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enroll_solution_rest_bad_request( + request_type=project_service.EnrollSolutionRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.enroll_solution(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.EnrollSolutionRequest, + dict, + ], +) +def test_enroll_solution_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "projects/sample1"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enroll_solution(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enroll_solution_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProjectServiceRestInterceptor, "post_enroll_solution" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_enroll_solution" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.EnrollSolutionRequest.pb( + project_service.EnrollSolutionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = project_service.EnrollSolutionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enroll_solution( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_enrolled_solutions_rest_bad_request( + request_type=project_service.ListEnrolledSolutionsRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_enrolled_solutions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.ListEnrolledSolutionsRequest, + dict, + ], +) +def test_list_enrolled_solutions_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = project_service.ListEnrolledSolutionsResponse( + enrolled_solutions=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project_service.ListEnrolledSolutionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_enrolled_solutions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project_service.ListEnrolledSolutionsResponse) + assert response.enrolled_solutions == [ + common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_enrolled_solutions_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_list_enrolled_solutions" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_list_enrolled_solutions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.ListEnrolledSolutionsRequest.pb( + project_service.ListEnrolledSolutionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project_service.ListEnrolledSolutionsResponse.to_json( + project_service.ListEnrolledSolutionsResponse() + ) + req.return_value.content = return_value + + request = project_service.ListEnrolledSolutionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project_service.ListEnrolledSolutionsResponse() + + client.list_enrolled_solutions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_logging_config_rest_bad_request( + request_type=project_service.GetLoggingConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/loggingConfig"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_logging_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.GetLoggingConfigRequest, + dict, + ], +) +def test_get_logging_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/loggingConfig"} + 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 = project.LoggingConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.LoggingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_logging_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.LoggingConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_logging_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_logging_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_get_logging_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.GetLoggingConfigRequest.pb( + project_service.GetLoggingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.LoggingConfig.to_json(project.LoggingConfig()) + req.return_value.content = return_value + + request = project_service.GetLoggingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.LoggingConfig() + + client.get_logging_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_logging_config_rest_bad_request( + request_type=project_service.UpdateLoggingConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"logging_config": {"name": "projects/sample1/loggingConfig"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_logging_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.UpdateLoggingConfigRequest, + dict, + ], +) +def test_update_logging_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"logging_config": {"name": "projects/sample1/loggingConfig"}} + request_init["logging_config"] = { + "name": "projects/sample1/loggingConfig", + "default_log_generation_rule": { + "logging_level": 1, + "info_log_sample_rate": 0.21050000000000002, + }, + "service_log_generation_rules": [ + {"service_name": "service_name_value", "log_generation_rule": {}} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = project_service.UpdateLoggingConfigRequest.meta.fields[ + "logging_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["logging_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["logging_config"][field])): + del request_init["logging_config"][field][i][subfield] + else: + del request_init["logging_config"][field][subfield] + 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 = project.LoggingConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.LoggingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_logging_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.LoggingConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_logging_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_logging_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_update_logging_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.UpdateLoggingConfigRequest.pb( + project_service.UpdateLoggingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.LoggingConfig.to_json(project.LoggingConfig()) + req.return_value.content = return_value + + request = project_service.UpdateLoggingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.LoggingConfig() + + client.update_logging_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_alert_config_rest_bad_request( + request_type=project_service.GetAlertConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/alertConfig"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_alert_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.GetAlertConfigRequest, + dict, + ], +) +def test_get_alert_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/alertConfig"} + 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 = project.AlertConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.AlertConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_alert_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.AlertConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_alert_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_alert_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_get_alert_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.GetAlertConfigRequest.pb( + project_service.GetAlertConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.AlertConfig.to_json(project.AlertConfig()) + req.return_value.content = return_value + + request = project_service.GetAlertConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.AlertConfig() + + client.get_alert_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_alert_config_rest_bad_request( + request_type=project_service.UpdateAlertConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_alert_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.UpdateAlertConfigRequest, + dict, + ], +) +def test_update_alert_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} + request_init["alert_config"] = { + "name": "projects/sample1/alertConfig", + "alert_policies": [ + { + "alert_group": "alert_group_value", + "enroll_status": 1, + "recipients": [{"email_address": "email_address_value"}], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = project_service.UpdateAlertConfigRequest.meta.fields["alert_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["alert_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["alert_config"][field])): + del request_init["alert_config"][field][i][subfield] + else: + del request_init["alert_config"][field][subfield] + 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 = project.AlertConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.AlertConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_alert_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.AlertConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_alert_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_alert_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_update_alert_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.UpdateAlertConfigRequest.pb( + project_service.UpdateAlertConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.AlertConfig.to_json(project.AlertConfig()) + req.return_value.content = return_value + + request = project_service.UpdateAlertConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.AlertConfig() + + client.update_alert_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_project_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_project), "__call__") as call: + client.get_project(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetProjectRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_accept_terms_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.accept_terms), "__call__") as call: + client.accept_terms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.AcceptTermsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_enroll_solution_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.enroll_solution), "__call__") as call: + client.enroll_solution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.EnrollSolutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_enrolled_solutions_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_enrolled_solutions), "__call__" + ) as call: + client.list_enrolled_solutions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.ListEnrolledSolutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_logging_config_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_logging_config), "__call__" + ) as call: + client.get_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetLoggingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_logging_config_empty_call_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_logging_config), "__call__" + ) as call: + client.update_logging_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateLoggingConfigRequest() + + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_alert_config_empty_call_rest(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ProjectServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + client.get_alert_config(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() - transport = transports.ProjectServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_alert_config_empty_call_rest(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + client.update_alert_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProjectServiceGrpcTransport, - transports.ProjectServiceGrpcAsyncIOTransport, - transports.ProjectServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProjectServiceClient.get_transport_class(transport_name)( + +def test_project_service_rest_lro_client(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -6986,23 +7334,6 @@ def test_project_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_project_service_rest_lro_client(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -7438,141 +7769,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7600,7 +7796,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7655,7 +7851,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7702,7 +7898,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -7745,7 +7941,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -7800,7 +7996,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -7847,7 +8043,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -7863,22 +8059,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_search_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_search_service.py index 47e49cf2aaac..8a55cb11fdb8 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_search_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_search_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,14 +53,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2alpha.services.search_service import ( SearchServiceAsyncClient, @@ -54,10 +63,24 @@ from google.cloud.retail_v2alpha.types import common, search_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1161,25 +1184,6 @@ def test_search(request_type, transport: str = "grpc"): assert response.applied_controls == ["applied_controls_value"] -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - def test_search_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1259,41 +1263,13 @@ def test_search_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - ) - response = await client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - @pytest.mark.asyncio async def test_search_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1332,7 +1308,7 @@ async def test_search_async( transport: str = "grpc_asyncio", request_type=search_service.SearchRequest ): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1408,7 +1384,7 @@ def test_search_field_headers(): @pytest.mark.asyncio async def test_search_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1537,7 +1513,7 @@ def test_search_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_async_pager(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1565,7 @@ async def test_search_async_pager(): @pytest.mark.asyncio async def test_search_async_pages(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,58 +1609,6 @@ async def test_search_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - search_service.SearchRequest, - dict, - ], -) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == "corrected_query_value" - assert response.attribution_token == "attribution_token_value" - assert response.next_page_token == "next_page_token_value" - assert response.redirect_uri == "redirect_uri_value" - assert response.applied_controls == ["applied_controls_value"] - - def test_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1815,87 +1739,6 @@ def test_search_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" - ) as post, mock.patch.object( - transports.SearchServiceRestInterceptor, "pre_search" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - 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 = search_service.SearchResponse.to_json( - search_service.SearchResponse() - ) - - request = search_service.SearchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request( - transport: str = "rest", request_type=search_service.SearchRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.search(request) - - def test_search_rest_pager(transport: str = "rest"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2053,76 +1896,433 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = SearchServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + call.return_value = search_service.SearchResponse() + client.search(request=None) -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + assert args[0] == request_msg -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "search", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = SearchServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_empty_call_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + ) + await client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SearchServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_rest_bad_request(request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search(request) + + +@pytest.mark.parametrize( + "request_type", + [ + search_service.SearchRequest, + dict, + ], +) +def test_search_rest_call_success(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == "corrected_query_value" + assert response.attribution_token == "attribution_token_value" + assert response.next_page_token == "next_page_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.applied_controls == ["applied_controls_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" + ) as post, mock.patch.object( + transports.SearchServiceRestInterceptor, "pre_search" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = search_service.SearchResponse.to_json( + search_service.SearchResponse() + ) + req.return_value.content = return_value + + request = search_service.SearchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2alpha.services.search_service.transports.SearchServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search", + "get_operation", + "list_operations", + ) + 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_search_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.retail_v2alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages" @@ -2739,141 +2939,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2901,7 +2966,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2956,7 +3021,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3003,7 +3068,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3046,7 +3111,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3101,7 +3166,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3148,7 +3213,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3164,22 +3229,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py index 1aeaecb11264..3d2c0a89137a 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_serving_config_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2alpha.services.serving_config_service import ( ServingConfigServiceAsyncClient, @@ -58,10 +67,24 @@ from google.cloud.retail_v2alpha.types import serving_config_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1268,27 +1291,6 @@ def test_create_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - def test_create_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1361,48 +1363,6 @@ def test_create_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - @pytest.mark.asyncio async def test_create_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1411,7 +1371,7 @@ async def test_create_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1451,7 +1411,7 @@ async def test_create_serving_config_async( request_type=serving_config_service.CreateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1560,7 +1520,7 @@ def test_create_serving_config_field_headers(): @pytest.mark.asyncio async def test_create_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1644,7 +1604,7 @@ def test_create_serving_config_flattened_error(): @pytest.mark.asyncio async def test_create_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1683,7 +1643,7 @@ async def test_create_serving_config_flattened_async(): @pytest.mark.asyncio async def test_create_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1732,27 +1692,6 @@ def test_delete_serving_config(request_type, transport: str = "grpc"): assert response is None -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - def test_delete_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1823,27 +1762,6 @@ def test_delete_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - @pytest.mark.asyncio async def test_delete_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1852,7 +1770,7 @@ async def test_delete_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1892,7 +1810,7 @@ async def test_delete_serving_config_async( request_type=serving_config_service.DeleteServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1957,7 +1875,7 @@ def test_delete_serving_config_field_headers(): @pytest.mark.asyncio async def test_delete_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2029,7 +1947,7 @@ def test_delete_serving_config_flattened_error(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2058,7 +1976,7 @@ async def test_delete_serving_config_flattened_async(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2147,27 +2065,6 @@ def test_update_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - def test_update_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2234,48 +2131,6 @@ def test_update_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - @pytest.mark.asyncio async def test_update_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2284,7 +2139,7 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2324,7 +2179,7 @@ async def test_update_serving_config_async( request_type=serving_config_service.UpdateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2433,7 +2288,7 @@ def test_update_serving_config_field_headers(): @pytest.mark.asyncio async def test_update_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2512,7 +2367,7 @@ def test_update_serving_config_flattened_error(): @pytest.mark.asyncio async def test_update_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2547,7 +2402,7 @@ async def test_update_serving_config_flattened_async(): @pytest.mark.asyncio async def test_update_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2637,27 +2492,6 @@ def test_get_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - def test_get_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2727,48 +2561,6 @@ def test_get_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - @pytest.mark.asyncio async def test_get_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2777,7 +2569,7 @@ async def test_get_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2817,7 +2609,7 @@ async def test_get_serving_config_async( request_type=serving_config_service.GetServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2926,7 +2718,7 @@ def test_get_serving_config_field_headers(): @pytest.mark.asyncio async def test_get_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3000,7 +2792,7 @@ def test_get_serving_config_flattened_error(): @pytest.mark.asyncio async def test_get_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3031,7 +2823,7 @@ async def test_get_serving_config_flattened_async(): @pytest.mark.asyncio async def test_get_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3081,27 +2873,6 @@ def test_list_serving_configs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - def test_list_serving_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3173,31 +2944,6 @@ def test_list_serving_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_serving_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - @pytest.mark.asyncio async def test_list_serving_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3206,7 +2952,7 @@ async def test_list_serving_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3246,7 +2992,7 @@ async def test_list_serving_configs_async( request_type=serving_config_service.ListServingConfigsRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3316,7 +3062,7 @@ def test_list_serving_configs_field_headers(): @pytest.mark.asyncio async def test_list_serving_configs_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3390,7 +3136,7 @@ def test_list_serving_configs_flattened_error(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3421,7 +3167,7 @@ async def test_list_serving_configs_flattened_async(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3535,7 +3281,7 @@ def test_list_serving_configs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_serving_configs_async_pager(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3587,7 +3333,7 @@ async def test_list_serving_configs_async_pager(): @pytest.mark.asyncio async def test_list_serving_configs_async_pages(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3710,25 +3456,6 @@ def test_add_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - def test_add_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3794,46 +3521,6 @@ def test_add_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - @pytest.mark.asyncio async def test_add_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3842,7 +3529,7 @@ async def test_add_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3882,7 +3569,7 @@ async def test_add_control_async( request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3987,7 +3674,7 @@ def test_add_control_field_headers(): @pytest.mark.asyncio async def test_add_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4057,7 +3744,7 @@ def test_add_control_flattened_error(): @pytest.mark.asyncio async def test_add_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4086,7 +3773,7 @@ async def test_add_control_flattened_async(): @pytest.mark.asyncio async def test_add_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4173,25 +3860,6 @@ def test_remove_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - def test_remove_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4257,46 +3925,6 @@ def test_remove_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - @pytest.mark.asyncio async def test_remove_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4305,7 +3933,7 @@ async def test_remove_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4345,7 +3973,7 @@ async def test_remove_control_async( request_type=serving_config_service.RemoveControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4450,7 +4078,7 @@ def test_remove_control_field_headers(): @pytest.mark.asyncio async def test_remove_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4520,7 +4148,7 @@ def test_remove_control_flattened_error(): @pytest.mark.asyncio async def test_remove_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4549,7 +4177,7 @@ async def test_remove_control_flattened_async(): @pytest.mark.asyncio async def test_remove_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4561,236 +4189,45 @@ async def test_remove_control_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.CreateServingConfigRequest, - dict, - ], -) -def test_create_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["serving_config"] = { - "name": "name_value", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ - "serving_config" - ] + # Ensure method has been cached + assert ( + client._transport.create_serving_config + in client._transport._wrapped_methods + ) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_serving_config + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_serving_config(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.create_serving_config(request) - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_serving_config - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_serving_config - ] = mock_rpc - - request = {} - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_serving_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 def test_create_serving_config_rest_required_fields( @@ -4901,88 +4338,6 @@ def test_create_serving_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.CreateServingConfigRequest.pb( - serving_config_service.CreateServingConfigRequest() - ) - 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 = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() - ) - - request = serving_config_service.CreateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() - - client.create_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.CreateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_serving_config(request) - - def test_create_serving_config_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5046,49 +4401,6 @@ def test_create_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_create_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.DeleteServingConfigRequest, - dict, - ], -) -def test_delete_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_serving_config(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5210,84 +4522,8 @@ def test_delete_serving_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" - ) as pre: - pre.assert_not_called() - pb_message = serving_config_service.DeleteServingConfigRequest.pb( - serving_config_service.DeleteServingConfigRequest() - ) - 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() - - request = serving_config_service.DeleteServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.DeleteServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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.delete_serving_config(request) - - -def test_delete_serving_config_rest_flattened(): - client = ServingConfigServiceClient( +def test_delete_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -5343,168 +4579,152 @@ def test_delete_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_delete_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_serving_config + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_serving_config + ] = mock_rpc + + request = {} + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_serving_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_serving_config_rest_required_fields( + request_type=serving_config_service.UpdateServingConfigRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_serving_config._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_serving_config._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 -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.UpdateServingConfigRequest, - dict, - ], -) -def test_update_serving_config_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - request_init["serving_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ - "serving_config" - ] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.update_serving_config(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_serving_config_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.update_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - request = request_type(**request_init) + +def test_update_serving_config_rest_flattened(): + client = ServingConfigServiceClient( + 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + return_value = gcr_serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + serving_config=gcr_serving_config.ServingConfig(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() @@ -5512,39 +4732,39 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + client.update_serving_config(**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/v2alpha/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_serving_config_rest_flattened_error(transport: str = "rest"): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_update_serving_config_rest_use_cached_wrapped_rpc(): +def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5559,8 +4779,7 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_serving_config - in client._transport._wrapped_methods + client._transport.get_serving_config in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5569,28 +4788,29 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_serving_config + client._transport.get_serving_config ] = mock_rpc request = {} - client.update_serving_config(request) + client.get_serving_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_serving_config(request) + client.get_serving_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_serving_config_rest_required_fields( - request_type=serving_config_service.UpdateServingConfigRequest, +def test_get_serving_config_rest_required_fields( + request_type=serving_config_service.GetServingConfigRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5601,19 +4821,21 @@ def test_update_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_serving_config._get_unset_required_fields(jsonified_request) + ).get_serving_config._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() - ).update_serving_config._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",)) + ).get_serving_config._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 = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5622,7 +4844,7 @@ def test_update_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() + return_value = serving_config.ServingConfig() # 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 @@ -5634,172 +4856,82 @@ def test_update_serving_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) + response = client.get_serving_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_serving_config_rest_unset_required_fields(): +def test_get_serving_config_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) + unset_fields = transport.get_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_get_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.UpdateServingConfigRequest.pb( - serving_config_service.UpdateServingConfigRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - request = serving_config_service.UpdateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.update_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_serving_config(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) -def test_update_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.UpdateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - 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_serving_config(request) - - -def test_update_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config=gcr_serving_config.ServingConfig(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 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_serving_config(**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/v2alpha/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" - % client.transport._host, - args[1], - ) - - -def test_update_serving_config_rest_flattened_error(transport: str = "rest"): +def test_get_serving_config_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5808,101 +4940,13 @@ def test_update_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.GetServingConfigRequest, - dict, - ], -) -def test_get_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = serving_config.ServingConfig( + client.get_serving_config( + serving_config_service.GetServingConfigRequest(), name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - -def test_get_serving_config_rest_use_cached_wrapped_rpc(): +def test_list_serving_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5917,7 +4961,7 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_serving_config in client._transport._wrapped_methods + client._transport.list_serving_configs in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5926,29 +4970,29 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_serving_config + client._transport.list_serving_configs ] = mock_rpc request = {} - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_serving_config_rest_required_fields( - request_type=serving_config_service.GetServingConfigRequest, +def test_list_serving_configs_rest_required_fields( + request_type=serving_config_service.ListServingConfigsRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5959,21 +5003,28 @@ def test_get_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5982,7 +5033,7 @@ def test_get_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse() # 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 @@ -6003,130 +5054,57 @@ def test_get_serving_config_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_serving_config(request) + response = client.list_serving_configs(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_serving_config_rest_unset_required_fields(): +def test_list_serving_configs_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_list_serving_configs_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_get_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.GetServingConfigRequest.pb( - serving_config_service.GetServingConfigRequest() - ) - 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 = serving_config.ServingConfig.to_json( - serving_config.ServingConfig() - ) - - request = serving_config_service.GetServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config.ServingConfig() - - client.get_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_serving_config_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.GetServingConfigRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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_serving_config(request) - - -def test_get_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = serving_config.ServingConfig() + # 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 = serving_config_service.ListServingConfigsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -6134,25 +5112,27 @@ def test_get_serving_config_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_serving_config(**mock_args) + client.list_serving_configs(**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/v2alpha/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + "%s/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" % client.transport._host, args[1], ) -def test_get_serving_config_rest_flattened_error(transport: str = "rest"): +def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6161,61 +5141,79 @@ def test_get_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_serving_config( - serving_config_service.GetServingConfigRequest(), - name="name_value", + client.list_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent="parent_value", ) -def test_get_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.ListServingConfigsRequest, - dict, - ], -) -def test_list_serving_configs_rest(request_type): +def test_list_serving_configs_rest_pager(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token="abc", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token="def", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token="ghi", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), ) + # Two responses for two calls + response = response + response - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value + # Wrap the values into proper Response objs + response = tuple( + serving_config_service.ListServingConfigsResponse.to_json(x) + for x in response ) - json_return_value = json_format.MessageToJson(return_value) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_serving_configs(request) + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == "next_page_token_value" + pager = client.list_serving_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) for i in results) + + pages = list(client.list_serving_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_serving_configs_rest_use_cached_wrapped_rpc(): +def test_add_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6229,39 +5227,36 @@ def test_list_serving_configs_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_serving_configs in client._transport._wrapped_methods - ) + assert client._transport.add_control in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_serving_configs - ] = mock_rpc + client._transport._wrapped_methods[client._transport.add_control] = mock_rpc request = {} - client.list_serving_configs(request) + client.add_control(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_serving_configs(request) + client.add_control(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_serving_configs_rest_required_fields( - request_type=serving_config_service.ListServingConfigsRequest, +def test_add_control_rest_required_fields( + request_type=serving_config_service.AddControlRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6272,28 +5267,24 @@ def test_list_serving_configs_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) + ).add_control._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" + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).add_control._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" + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6302,7 +5293,7 @@ def test_list_serving_configs_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # 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 @@ -6314,132 +5305,238 @@ def test_list_serving_configs_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_serving_configs(request) + response = client.add_control(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_serving_configs_rest_unset_required_fields(): +def test_add_control_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + unset_fields = transport.add_control._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "servingConfig", + "controlId", ) ) - & set(("parent",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_serving_configs_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_add_control_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_list_serving_configs" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.ListServingConfigsRequest.pb( - serving_config_service.ListServingConfigsRequest() - ) - 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 = ( - serving_config_service.ListServingConfigsResponse.to_json( - serving_config_service.ListServingConfigsResponse() - ) - ) + # 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 = gcr_serving_config.ServingConfig() - request = serving_config_service.ListServingConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config_service.ListServingConfigsResponse() + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } - client.list_serving_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + serving_config="serving_config_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + client.add_control(**mock_args) -def test_list_serving_configs_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.ListServingConfigsRequest, -): + # 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/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" + % client.transport._host, + args[1], + ) + + +def test_add_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config="serving_config_value", + ) + + +def test_remove_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_control in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + + request = {} + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_control(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_control_rest_required_fields( + request_type=serving_config_service.RemoveControlRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # 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.list_serving_configs(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_list_serving_configs_rest_flattened(): + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" + + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.remove_control(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_control_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_control._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "servingConfig", + "controlId", + ) + ) + ) + + +def test_remove_control_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6448,16 +5545,16 @@ def test_list_serving_configs_rest_flattened(): # 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 = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + serving_config="serving_config_value", ) mock_args.update(sample_request) @@ -6465,27 +5562,25 @@ def test_list_serving_configs_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_serving_configs(**mock_args) + client.remove_control(**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/v2alpha/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" + "%s/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" % client.transport._host, args[1], ) -def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): +def test_remove_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6494,101 +5589,1286 @@ def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent="parent_value", + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config="serving_config_value", ) -def test_list_serving_configs_rest_pager(transport: str = "rest"): - client = ServingConfigServiceClient( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token="abc", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token="def", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token="ghi", - ), + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ServingConfigServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + call.return_value = None + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ServingConfigServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_serving_configs_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), + next_page_token="next_page_token_value", + ) + ) + await client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ServingConfigServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_serving_config_rest_bad_request( + request_type=serving_config_service.CreateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.CreateServingConfigRequest, + dict, + ], +) +def test_create_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["serving_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - serving_config_service.ListServingConfigsResponse.to_json(x) - for x in response + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.CreateServingConfigRequest.pb( + serving_config_service.CreateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.CreateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.create_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_serving_config_rest_bad_request( + request_type=serving_config_service.DeleteServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.DeleteServingConfigRequest, + dict, + ], +) +def test_delete_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_serving_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" + ) as pre: + pre.assert_not_called() + pb_message = serving_config_service.DeleteServingConfigRequest.pb( + serving_config_service.DeleteServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = serving_config_service.DeleteServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_serving_config_rest_bad_request( + request_type=serving_config_service.UpdateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.UpdateServingConfigRequest, + dict, + ], +) +def test_update_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + request_init["serving_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.UpdateServingConfigRequest.pb( + serving_config_service.UpdateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, } - pager = client.list_serving_configs(request=sample_request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.UpdateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.update_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) for i in results) +def test_get_serving_config_rest_bad_request( + request_type=serving_config_service.GetServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + request = request_type(**request_init) - pages = list(client.list_serving_configs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_serving_config(request) @pytest.mark.parametrize( "request_type", [ - serving_config_service.AddControlRequest, + serving_config_service.GetServingConfigRequest, dict, ], ) -def test_add_control_rest(request_type): +def test_get_serving_config_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } 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 = gcr_serving_config.ServingConfig( + return_value = serving_config.ServingConfig( name="name_value", display_name="display_name_value", model_id="model_id_value", @@ -6603,25 +6883,25 @@ def test_add_control_rest(request_type): replacement_control_ids=["replacement_control_ids_value"], ignore_control_ids=["ignore_control_ids_value"], diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, enable_category_filter_level="enable_category_filter_level_value", ignore_recs_denylist=True, solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.add_control(request) + response = client.get_serving_config(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) + assert isinstance(response, serving_config.ServingConfig) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.model_id == "model_id_value" @@ -6640,147 +6920,138 @@ def test_add_control_rest(request_type): assert response.diversity_level == "diversity_level_value" assert ( response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) assert response.enable_category_filter_level == "enable_category_filter_level_value" assert response.ignore_recs_denylist is True assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.add_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_get_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.GetServingConfigRequest.pb( + serving_config_service.GetServingConfigRequest() ) - client._transport._wrapped_methods[client._transport.add_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.add_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = serving_config.ServingConfig.to_json( + serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.GetServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = serving_config.ServingConfig() - client.add_control(request) + client.get_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_add_control_rest_required_fields( - request_type=serving_config_service.AddControlRequest, +def test_list_serving_configs_rest_bad_request( + request_type=serving_config_service.ListServingConfigsRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_serving_configs(request) - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.ListServingConfigsRequest, + dict, + ], +) +def test_list_serving_configs_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() # 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 - - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.add_control(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = serving_config_service.ListServingConfigsResponse( + next_page_token="next_page_token_value", + ) -def test_add_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.add_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) + # Convert return value to protobuf type + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value ) - ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_serving_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_control_rest_interceptors(null_interceptor): +def test_list_serving_configs_rest_interceptors(null_interceptor): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6788,19 +7059,20 @@ def test_add_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_add_control" + transports.ServingConfigServiceRestInterceptor, "post_list_serving_configs" ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_add_control" + transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = serving_config_service.AddControlRequest.pb( - serving_config_service.AddControlRequest() + pb_message = serving_config_service.ListServingConfigsRequest.pb( + serving_config_service.ListServingConfigsRequest() ) transcode.return_value = { "method": "post", @@ -6809,22 +7081,22 @@ def test_add_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse.to_json( + serving_config_service.ListServingConfigsResponse() ) + req.return_value.content = return_value - request = serving_config_service.AddControlRequest() + request = serving_config_service.ListServingConfigsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + post.return_value = serving_config_service.ListServingConfigsResponse() - client.add_control( + client.list_serving_configs( request, metadata=[ ("key", "val"), @@ -6837,13 +7109,11 @@ def test_add_control_rest_interceptors(null_interceptor): def test_add_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.AddControlRequest + request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" @@ -6855,89 +7125,25 @@ def test_add_control_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.add_control(request) -def test_add_control_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.add_control(**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/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" - % client.transport._host, - args[1], - ) - - -def test_add_control_rest_flattened_error(transport: str = "rest"): - client = ServingConfigServiceClient( - 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.add_control( - serving_config_service.AddControlRequest(), - serving_config="serving_config_value", - ) - - -def test_add_control_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - serving_config_service.RemoveControlRequest, + serving_config_service.AddControlRequest, dict, ], ) -def test_remove_control_rest(request_type): +def test_add_control_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -6971,15 +7177,15 @@ def test_remove_control_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_control(request) + response = client.add_control(request) # Establish that the response is the type that we expect. assert isinstance(response, gcr_serving_config.ServingConfig) @@ -7008,136 +7214,168 @@ def test_remove_control_rest(request_type): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.remove_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_control_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_add_control" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_add_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.AddControlRequest.pb( + serving_config_service.AddControlRequest() ) - client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.remove_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.AddControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) + client.add_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_remove_control_rest_required_fields( +def test_remove_control_rest_bad_request( request_type=serving_config_service.RemoveControlRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_control(request) - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.RemoveControlRequest, + dict, + ], +) +def test_remove_control_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.remove_control(request) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_remove_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_control(request) - unset_fields = transport.remove_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7149,6 +7387,7 @@ def test_remove_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -7170,12 +7409,12 @@ def test_remove_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( + return_value = gcr_serving_config.ServingConfig.to_json( gcr_serving_config.ServingConfig() ) + req.return_value.content = return_value request = serving_config_service.RemoveControlRequest() metadata = [ @@ -7197,19 +7436,20 @@ def test_remove_control_rest_interceptors(null_interceptor): post.assert_called_once() -def test_remove_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.RemoveControlRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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( @@ -7217,181 +7457,265 @@ def test_remove_control_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.remove_control(request) + client.get_operation(request) -def test_remove_control_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + 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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.remove_control(**mock_args) + response = client.get_operation(request) - # 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/v2alpha/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_remove_control_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config="serving_config_value", - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -def test_remove_control_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert client is not None - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + client.update_serving_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + client.get_serving_config(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + client.add_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -8028,141 +8352,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8190,7 +8379,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8245,7 +8434,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8292,7 +8481,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8335,7 +8524,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8390,7 +8579,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8437,7 +8626,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8453,22 +8642,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_user_event_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_user_event_service.py index 097f321321e8..b3757ca0d10b 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_user_event_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2alpha/test_user_event_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import httpbody_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -49,17 +66,9 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2alpha.services.user_event_service import ( UserEventServiceAsyncClient, @@ -78,10 +87,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1237,25 +1260,6 @@ def test_write_user_event(request_type, transport: str = "grpc"): assert response.entity == "entity_value" -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - def test_write_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1321,43 +1325,6 @@ def test_write_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_write_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - user_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - ) - response = await client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - @pytest.mark.asyncio async def test_write_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1366,7 +1333,7 @@ async def test_write_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1406,7 +1373,7 @@ async def test_write_user_event_async( request_type=user_event_service.WriteUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1500,7 +1467,7 @@ def test_write_user_event_field_headers(): @pytest.mark.asyncio async def test_write_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1569,27 +1536,6 @@ def test_collect_user_event(request_type, transport: str = "grpc"): assert response.data == b"data_blob" -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - def test_collect_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1667,32 +1613,6 @@ def test_collect_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_collect_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - ) - response = await client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - @pytest.mark.asyncio async def test_collect_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1701,7 +1621,7 @@ async def test_collect_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1741,7 +1661,7 @@ async def test_collect_user_event_async( request_type=user_event_service.CollectUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1813,7 +1733,7 @@ def test_collect_user_event_field_headers(): @pytest.mark.asyncio async def test_collect_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1879,27 +1799,6 @@ def test_purge_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - def test_purge_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1974,29 +1873,6 @@ def test_purge_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - @pytest.mark.asyncio async def test_purge_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2005,7 +1881,7 @@ async def test_purge_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2049,7 +1925,7 @@ async def test_purge_user_events_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2116,7 +1992,7 @@ def test_purge_user_events_field_headers(): @pytest.mark.asyncio async def test_purge_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2182,27 +2058,6 @@ def test_import_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - def test_import_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2277,29 +2132,6 @@ def test_import_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - @pytest.mark.asyncio async def test_import_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2308,7 +2140,7 @@ async def test_import_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2352,7 +2184,7 @@ async def test_import_user_events_async( transport: str = "grpc_asyncio", request_type=import_config.ImportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2419,7 +2251,7 @@ def test_import_user_events_field_headers(): @pytest.mark.asyncio async def test_import_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2485,27 +2317,6 @@ def test_export_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportUserEventsRequest() - - def test_export_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2582,29 +2393,6 @@ def test_export_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportUserEventsRequest() - - @pytest.mark.asyncio async def test_export_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2613,7 +2401,7 @@ async def test_export_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2657,7 +2445,7 @@ async def test_export_user_events_async( transport: str = "grpc_asyncio", request_type=export_config.ExportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2724,7 +2512,7 @@ def test_export_user_events_field_headers(): @pytest.mark.asyncio async def test_export_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2790,27 +2578,6 @@ def test_rejoin_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - def test_rejoin_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2886,39 +2653,16 @@ def test_rejoin_user_events_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_rejoin_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_rejoin_user_events_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -2961,7 +2705,7 @@ async def test_rejoin_user_events_async( request_type=user_event_service.RejoinUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3028,7 +2772,7 @@ def test_rejoin_user_events_field_headers(): @pytest.mark.asyncio async def test_rejoin_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3059,311 +2803,51 @@ async def test_rejoin_user_events_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.WriteUserEventRequest, - dict, - ], -) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_write_user_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["user_event"] = { - "event_type": "event_type_value", - "visitor_id": "visitor_id_value", - "session_id": "session_id_value", - "event_time": {"seconds": 751, "nanos": 543}, - "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], - "attribution_token": "attribution_token_value", - "product_details": [ - { - "product": { - "expire_time": {}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": [ - "color_families_value1", - "color_families_value2", - ], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - }, - "quantity": {}, - } - ], - "completion_detail": { - "completion_attribution_token": "completion_attribution_token_value", - "selected_suggestion": "selected_suggestion_value", - "selected_position": 1821, - }, - "attributes": {}, - "cart_id": "cart_id_value", - "purchase_transaction": { - "id": "id_value", - "revenue": 0.762, - "tax": 0.333, - "cost": 0.441, - "currency_code": "currency_code_value", - }, - "search_query": "search_query_value", - "filter": "filter_value", - "order_by": "order_by_value", - "offset": 647, - "page_categories": ["page_categories_value1", "page_categories_value2"], - "user_info": { - "user_id": "user_id_value", - "ip_address": "ip_address_value", - "user_agent": "user_agent_value", - "direct_user_request": True, - }, - "uri": "uri_value", - "referrer_uri": "referrer_uri_value", - "page_view_id": "page_view_id_value", - "entity": "entity_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + # Ensure method has been cached + assert client._transport.write_user_event in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.write_user_event + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.write_user_event(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.write_user_event(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["user_event"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +def test_write_user_event_rest_required_fields( + request_type=user_event_service.WriteUserEventRequest, +): + transport_class = transports.UserEventServiceRestTransport - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["user_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][field][subfield] - 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_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == "event_type_value" - assert response.visitor_id == "visitor_id_value" - assert response.session_id == "session_id_value" - assert response.experiment_ids == ["experiment_ids_value"] - assert response.attribution_token == "attribution_token_value" - assert response.cart_id == "cart_id_value" - assert response.search_query == "search_query_value" - assert response.filter == "filter_value" - assert response.order_by == "order_by_value" - assert response.offset == 647 - assert response.page_categories == ["page_categories_value"] - assert response.uri == "uri_value" - assert response.referrer_uri == "referrer_uri_value" - assert response.page_view_id == "page_view_id_value" - assert response.entity == "entity_value" - - -def test_write_user_event_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.write_user_event in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.write_user_event - ] = mock_rpc - - request = {} - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.write_user_event(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_write_user_event_rest_required_fields( - request_type=user_event_service.WriteUserEventRequest, -): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" + request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3451,131 +2935,6 @@ def test_write_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_write_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb( - user_event_service.WriteUserEventRequest() - ) - 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_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.WriteUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.CollectUserEventRequest, - dict, - ], -) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == "content_type_value" - assert response.data == b"data_blob" - - def test_collect_user_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3736,138 +3095,18 @@ def test_collect_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_collect_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb( - user_event_service.CollectUserEventRequest() +def test_purge_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.CollectUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeUserEventsRequest, - dict, - ], -) -def test_purge_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.purge_user_events in client._transport._wrapped_methods @@ -3991,130 +3230,6 @@ def test_purge_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_purge_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_purge_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeUserEventsRequest.pb( - purge_config.PurgeUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = purge_config.PurgeUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_user_events_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.purge_user_events(request) - - -def test_purge_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportUserEventsRequest, - dict, - ], -) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4248,146 +3363,22 @@ def test_import_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_import_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_import_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb( - import_config.ImportUserEventsRequest() +def test_export_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = import_config.ImportUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportUserEventsRequest, - dict, - ], -) -def test_export_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.export_user_events in client._transport._wrapped_methods + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.export_user_events in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -4505,130 +3496,6 @@ def test_export_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_export_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_export_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportUserEventsRequest.pb( - export_config.ExportUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_user_events_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.export_user_events(request) - - -def test_export_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.RejoinUserEventsRequest, - dict, - ], -) -def test_rejoin_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.rejoin_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_rejoin_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4754,46 +3621,1346 @@ def test_rejoin_user_events_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rejoin_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.RejoinUserEventsRequest.pb( - user_event_service.RejoinUserEventsRequest() + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - request = user_event_service.RejoinUserEventsRequest() + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = UserEventServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserEventServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_write_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + ) + await client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_collect_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + ) + await client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_rejoin_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserEventServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_write_user_event_rest_bad_request( + request_type=user_event_service.WriteUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.write_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.WriteUserEventRequest, + dict, + ], +) +def test_write_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["user_event"] = { + "event_type": "event_type_value", + "visitor_id": "visitor_id_value", + "session_id": "session_id_value", + "event_time": {"seconds": 751, "nanos": 543}, + "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], + "attribution_token": "attribution_token_value", + "product_details": [ + { + "product": { + "expire_time": {}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": [ + "color_families_value1", + "color_families_value2", + ], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + }, + "quantity": {}, + } + ], + "completion_detail": { + "completion_attribution_token": "completion_attribution_token_value", + "selected_suggestion": "selected_suggestion_value", + "selected_position": 1821, + }, + "attributes": {}, + "cart_id": "cart_id_value", + "purchase_transaction": { + "id": "id_value", + "revenue": 0.762, + "tax": 0.333, + "cost": 0.441, + "currency_code": "currency_code_value", + }, + "search_query": "search_query_value", + "filter": "filter_value", + "order_by": "order_by_value", + "offset": 647, + "page_categories": ["page_categories_value1", "page_categories_value2"], + "user_info": { + "user_id": "user_id_value", + "ip_address": "ip_address_value", + "user_agent": "user_agent_value", + "direct_user_request": True, + }, + "uri": "uri_value", + "referrer_uri": "referrer_uri_value", + "page_view_id": "page_view_id_value", + "entity": "entity_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][field][subfield] + 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_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == "event_type_value" + assert response.visitor_id == "visitor_id_value" + assert response.session_id == "session_id_value" + assert response.experiment_ids == ["experiment_ids_value"] + assert response.attribution_token == "attribution_token_value" + assert response.cart_id == "cart_id_value" + assert response.search_query == "search_query_value" + assert response.filter == "filter_value" + assert response.order_by == "order_by_value" + assert response.offset == 647 + assert response.page_categories == ["page_categories_value"] + assert response.uri == "uri_value" + assert response.referrer_uri == "referrer_uri_value" + assert response.page_view_id == "page_view_id_value" + assert response.entity == "entity_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_write_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb( + user_event_service.WriteUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = user_event.UserEvent.to_json(user_event.UserEvent()) + req.return_value.content = return_value + + request = user_event_service.WriteUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request( + request_type=user_event_service.CollectUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.collect_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.CollectUserEventRequest, + dict, + ], +) +def test_collect_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == "content_type_value" + assert response.data == b"data_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_collect_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb( + user_event_service.CollectUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(httpbody_pb2.HttpBody()) + req.return_value.content = return_value + + request = user_event_service.CollectUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request( + request_type=purge_config.PurgeUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeUserEventsRequest, + dict, + ], +) +def test_purge_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_purge_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_purge_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeUserEventsRequest.pb( + purge_config.PurgeUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = purge_config.PurgeUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request( + request_type=import_config.ImportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportUserEventsRequest, + dict, + ], +) +def test_import_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_import_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_import_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb( + import_config.ImportUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = import_config.ImportUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_user_events_rest_bad_request( + request_type=export_config.ExportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportUserEventsRequest, + dict, + ], +) +def test_export_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_export_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_export_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportUserEventsRequest.pb( + export_config.ExportUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rejoin_user_events_rest_bad_request( + request_type=user_event_service.RejoinUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.rejoin_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.RejoinUserEventsRequest, + dict, + ], +) +def test_rejoin_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.rejoin_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rejoin_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.RejoinUserEventsRequest.pb( + user_event_service.RejoinUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = user_event_service.RejoinUserEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -4813,17 +4980,82 @@ def test_rejoin_user_events_rest_interceptors(null_interceptor): post.assert_called_once() -def test_rejoin_user_events_rest_bad_request( - transport: str = "rest", request_type=user_event_service.RejoinUserEventsRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -4831,122 +5063,200 @@ def test_rejoin_user_events_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.rejoin_user_events(request) + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_rejoin_user_events_rest_error(): + +def test_initialize_client_w_rest(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + client.export_user_events(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() - transport = transports.UserEventServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + client.rejoin_user_events(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -5190,23 +5500,6 @@ def test_user_event_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -5636,141 +5929,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5798,7 +5956,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5853,7 +6011,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5900,7 +6058,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5943,7 +6101,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5998,7 +6156,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6045,7 +6203,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6061,22 +6219,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_analytics_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_analytics_service.py index 323aa5eca1eb..da2226822679 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_analytics_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_analytics_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,14 +62,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2beta.services.analytics_service import ( AnalyticsServiceAsyncClient, @@ -62,10 +71,24 @@ from google.cloud.retail_v2beta.types import export_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1192,27 +1215,6 @@ def test_export_analytics_metrics(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_analytics_metrics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - def test_export_analytics_metrics_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,29 +1292,6 @@ def test_export_analytics_metrics_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_analytics_metrics_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_analytics_metrics), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_analytics_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportAnalyticsMetricsRequest() - - @pytest.mark.asyncio async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1321,7 +1300,7 @@ async def test_export_analytics_metrics_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1345,7 @@ async def test_export_analytics_metrics_async( request_type=export_config.ExportAnalyticsMetricsRequest, ): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_export_analytics_metrics_field_headers(): @pytest.mark.asyncio async def test_export_analytics_metrics_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1464,41 +1443,6 @@ async def test_export_analytics_metrics_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportAnalyticsMetricsRequest, - dict, - ], -) -def test_export_analytics_metrics_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_analytics_metrics(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_analytics_metrics_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1633,95 +1577,6 @@ def test_export_analytics_metrics_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_analytics_metrics_rest_interceptors(null_interceptor): - transport = transports.AnalyticsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AnalyticsServiceRestInterceptor(), - ) - client = AnalyticsServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" - ) as post, mock.patch.object( - transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportAnalyticsMetricsRequest.pb( - export_config.ExportAnalyticsMetricsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportAnalyticsMetricsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_analytics_metrics( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_analytics_metrics_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportAnalyticsMetricsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.export_analytics_metrics(request) - - -def test_export_analytics_metrics_rest_error(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnalyticsServiceGrpcTransport( @@ -1814,87 +1669,444 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = AnalyticsServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = AnalyticsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.AnalyticsServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_analytics_metrics(request=None) -def test_analytics_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + assert args[0] == request_msg -def test_analytics_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2beta.services.analytics_service.transports.AnalyticsServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AnalyticsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "export_analytics_metrics", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = AnalyticsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - with pytest.raises(NotImplementedError): - transport.close() - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client +def test_initialize_client_w_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_analytics_metrics_empty_call_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_analytics_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + # Mock the actual call, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.retail_v2beta.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AnalyticsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_export_analytics_metrics_rest_bad_request( + request_type=export_config.ExportAnalyticsMetricsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_analytics_metrics(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportAnalyticsMetricsRequest, + dict, + ], +) +def test_export_analytics_metrics_rest_call_success(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_analytics_metrics(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_analytics_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsServiceRestInterceptor(), + ) + client = AnalyticsServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "post_export_analytics_metrics" + ) as post, mock.patch.object( + transports.AnalyticsServiceRestInterceptor, "pre_export_analytics_metrics" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportAnalyticsMetricsRequest.pb( + export_config.ExportAnalyticsMetricsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportAnalyticsMetricsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_analytics_metrics( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_analytics_metrics_empty_call_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_analytics_metrics), "__call__" + ) as call: + client.export_analytics_metrics(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportAnalyticsMetricsRequest() + + assert args[0] == request_msg + + +def test_analytics_service_rest_lro_client(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnalyticsServiceGrpcTransport, + ) + + +def test_analytics_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_analytics_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2beta.services.analytics_service.transports.AnalyticsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AnalyticsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "export_analytics_metrics", + "get_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_analytics_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.retail_v2beta.services.analytics_service.transports.AnalyticsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnalyticsServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", @@ -2064,23 +2276,6 @@ def test_analytics_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_analytics_service_rest_lro_client(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -2435,141 +2630,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = AnalyticsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2597,7 +2657,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2652,7 +2712,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2699,7 +2759,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2742,7 +2802,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2797,7 +2857,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2844,7 +2904,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = AnalyticsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2860,22 +2920,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = AnalyticsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AnalyticsServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AnalyticsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_catalog_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_catalog_service.py index 832c0e388794..281518132705 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_catalog_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_catalog_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,16 +54,8 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account 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.type import date_pb2 # type: ignore -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.retail_v2beta.services.catalog_service import ( CatalogServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2beta.types import catalog as gcr_catalog +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1160,25 +1183,6 @@ def test_list_catalogs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_catalogs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - def test_list_catalogs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1244,29 +1248,6 @@ def test_list_catalogs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_catalogs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_catalogs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogsRequest() - - @pytest.mark.asyncio async def test_list_catalogs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1275,7 +1256,7 @@ async def test_list_catalogs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1314,7 +1295,7 @@ async def test_list_catalogs_async( transport: str = "grpc_asyncio", request_type=catalog_service.ListCatalogsRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1380,7 +1361,7 @@ def test_list_catalogs_field_headers(): @pytest.mark.asyncio async def test_list_catalogs_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1450,7 +1431,7 @@ def test_list_catalogs_flattened_error(): @pytest.mark.asyncio async def test_list_catalogs_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1479,7 +1460,7 @@ async def test_list_catalogs_flattened_async(): @pytest.mark.asyncio async def test_list_catalogs_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1589,7 +1570,7 @@ def test_list_catalogs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_catalogs_async_pager(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1639,7 +1620,7 @@ async def test_list_catalogs_async_pager(): @pytest.mark.asyncio async def test_list_catalogs_async_pages(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1723,25 +1704,6 @@ def test_update_catalog(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" -def test_update_catalog_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - def test_update_catalog_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1801,30 +1763,6 @@ def test_update_catalog_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_catalog_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - ) - response = await client.update_catalog() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogRequest() - - @pytest.mark.asyncio async def test_update_catalog_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1833,7 +1771,7 @@ async def test_update_catalog_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1872,7 +1810,7 @@ async def test_update_catalog_async( transport: str = "grpc_asyncio", request_type=catalog_service.UpdateCatalogRequest ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1940,7 +1878,7 @@ def test_update_catalog_field_headers(): @pytest.mark.asyncio async def test_update_catalog_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2013,7 +1951,7 @@ def test_update_catalog_flattened_error(): @pytest.mark.asyncio async def test_update_catalog_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2044,7 +1982,7 @@ async def test_update_catalog_flattened_async(): @pytest.mark.asyncio async def test_update_catalog_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2092,27 +2030,6 @@ def test_set_default_branch(request_type, transport: str = "grpc"): assert response is None -def test_set_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - def test_set_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2186,27 +2103,6 @@ def test_set_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.set_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.SetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_set_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2215,7 +2111,7 @@ async def test_set_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2255,7 +2151,7 @@ async def test_set_default_branch_async( request_type=catalog_service.SetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2320,7 +2216,7 @@ def test_set_default_branch_field_headers(): @pytest.mark.asyncio async def test_set_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2392,7 +2288,7 @@ def test_set_default_branch_flattened_error(): @pytest.mark.asyncio async def test_set_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2421,7 +2317,7 @@ async def test_set_default_branch_flattened_async(): @pytest.mark.asyncio async def test_set_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2473,27 +2369,6 @@ def test_get_default_branch(request_type, transport: str = "grpc"): assert response.note == "note_value" -def test_get_default_branch_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - def test_get_default_branch_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2563,32 +2438,6 @@ def test_get_default_branch_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_default_branch_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_default_branch), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - ) - response = await client.get_default_branch() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetDefaultBranchRequest() - - @pytest.mark.asyncio async def test_get_default_branch_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2597,7 +2446,7 @@ async def test_get_default_branch_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2637,7 +2486,7 @@ async def test_get_default_branch_async( request_type=catalog_service.GetDefaultBranchRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2709,7 +2558,7 @@ def test_get_default_branch_field_headers(): @pytest.mark.asyncio async def test_get_default_branch_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2783,7 +2632,7 @@ def test_get_default_branch_flattened_error(): @pytest.mark.asyncio async def test_get_default_branch_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2814,7 +2663,7 @@ async def test_get_default_branch_flattened_async(): @pytest.mark.asyncio async def test_get_default_branch_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2887,27 +2736,6 @@ def test_get_completion_config(request_type, transport: str = "grpc"): ) -def test_get_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - def test_get_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2978,38 +2806,6 @@ def test_get_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.get_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCompletionConfigRequest() - - @pytest.mark.asyncio async def test_get_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3018,7 +2814,7 @@ async def test_get_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3058,7 +2854,7 @@ async def test_get_completion_config_async( request_type=catalog_service.GetCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3151,7 +2947,7 @@ def test_get_completion_config_field_headers(): @pytest.mark.asyncio async def test_get_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3225,7 +3021,7 @@ def test_get_completion_config_flattened_error(): @pytest.mark.asyncio async def test_get_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3256,7 +3052,7 @@ async def test_get_completion_config_flattened_async(): @pytest.mark.asyncio async def test_get_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3329,27 +3125,6 @@ def test_update_completion_config(request_type, transport: str = "grpc"): ) -def test_update_completion_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - def test_update_completion_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3416,38 +3191,6 @@ def test_update_completion_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_completion_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_completion_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", - ) - ) - response = await client.update_completion_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCompletionConfigRequest() - - @pytest.mark.asyncio async def test_update_completion_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3456,7 +3199,7 @@ async def test_update_completion_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3496,7 +3239,7 @@ async def test_update_completion_config_async( request_type=catalog_service.UpdateCompletionConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3589,7 +3332,7 @@ def test_update_completion_config_field_headers(): @pytest.mark.asyncio async def test_update_completion_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3668,7 +3411,7 @@ def test_update_completion_config_flattened_error(): @pytest.mark.asyncio async def test_update_completion_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3703,7 +3446,7 @@ async def test_update_completion_config_flattened_async(): @pytest.mark.asyncio async def test_update_completion_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3759,27 +3502,6 @@ def test_get_attributes_config(request_type, transport: str = "grpc"): ) -def test_get_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - def test_get_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3850,32 +3572,6 @@ def test_get_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.get_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetAttributesConfigRequest() - - @pytest.mark.asyncio async def test_get_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3884,7 +3580,7 @@ async def test_get_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3924,7 +3620,7 @@ async def test_get_attributes_config_async( request_type=catalog_service.GetAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3999,7 +3695,7 @@ def test_get_attributes_config_field_headers(): @pytest.mark.asyncio async def test_get_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4073,7 +3769,7 @@ def test_get_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4104,7 +3800,7 @@ async def test_get_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_get_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4159,27 +3855,6 @@ def test_update_attributes_config(request_type, transport: str = "grpc"): ) -def test_update_attributes_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - def test_update_attributes_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4246,32 +3921,6 @@ def test_update_attributes_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_attributes_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_attributes_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.update_attributes_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateAttributesConfigRequest() - - @pytest.mark.asyncio async def test_update_attributes_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4280,7 +3929,7 @@ async def test_update_attributes_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4320,7 +3969,7 @@ async def test_update_attributes_config_async( request_type=catalog_service.UpdateAttributesConfigRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4395,7 +4044,7 @@ def test_update_attributes_config_field_headers(): @pytest.mark.asyncio async def test_update_attributes_config_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4474,7 +4123,7 @@ def test_update_attributes_config_flattened_error(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4509,7 +4158,7 @@ async def test_update_attributes_config_flattened_async(): @pytest.mark.asyncio async def test_update_attributes_config_flattened_error_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4565,27 +4214,6 @@ def test_add_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_add_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - def test_add_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4656,32 +4284,6 @@ def test_add_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.add_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.AddCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4690,7 +4292,7 @@ async def test_add_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4730,7 +4332,7 @@ async def test_add_catalog_attribute_async( request_type=catalog_service.AddCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4805,7 +4407,7 @@ def test_add_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_add_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4879,27 +4481,6 @@ def test_remove_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_remove_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - def test_remove_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4972,32 +4553,6 @@ def test_remove_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.remove_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.RemoveCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5006,7 +4561,7 @@ async def test_remove_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5046,7 +4601,7 @@ async def test_remove_catalog_attribute_async( request_type=catalog_service.RemoveCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5121,7 +4676,7 @@ def test_remove_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_remove_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5192,27 +4747,6 @@ def test_batch_remove_catalog_attributes(request_type, transport: str = "grpc"): assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] -def test_batch_remove_catalog_attributes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_remove_catalog_attributes), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_remove_catalog_attributes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.BatchRemoveCatalogAttributesRequest() - - def test_batch_remove_catalog_attributes_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5283,32 +4817,6 @@ def test_batch_remove_catalog_attributes_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_batch_remove_catalog_attributes_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_remove_catalog_attributes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog_service.BatchRemoveCatalogAttributesResponse( - deleted_catalog_attributes=["deleted_catalog_attributes_value"], - reset_catalog_attributes=["reset_catalog_attributes_value"], - ) - ) - response = await client.batch_remove_catalog_attributes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.BatchRemoveCatalogAttributesRequest() - - @pytest.mark.asyncio async def test_batch_remove_catalog_attributes_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5317,7 +4825,7 @@ async def test_batch_remove_catalog_attributes_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5357,7 +4865,7 @@ async def test_batch_remove_catalog_attributes_async( request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5429,7 +4937,7 @@ def test_batch_remove_catalog_attributes_field_headers(): @pytest.mark.asyncio async def test_batch_remove_catalog_attributes_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5503,27 +5011,6 @@ def test_replace_catalog_attribute(request_type, transport: str = "grpc"): ) -def test_replace_catalog_attribute_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - def test_replace_catalog_attribute_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5594,32 +5081,6 @@ def test_replace_catalog_attribute_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_replace_catalog_attribute_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_catalog_attribute), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - ) - response = await client.replace_catalog_attribute() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ReplaceCatalogAttributeRequest() - - @pytest.mark.asyncio async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5628,7 +5089,7 @@ async def test_replace_catalog_attribute_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5668,7 +5129,7 @@ async def test_replace_catalog_attribute_async( request_type=catalog_service.ReplaceCatalogAttributeRequest, ): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5743,7 +5204,7 @@ def test_replace_catalog_attribute_field_headers(): @pytest.mark.asyncio async def test_replace_catalog_attribute_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5774,46 +5235,6 @@ async def test_replace_catalog_attribute_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.ListCatalogsRequest, - dict, - ], -) -def test_list_catalogs_rest(request_type): - client = CatalogServiceClient( - 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 = catalog_service.ListCatalogsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.ListCatalogsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_catalogs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCatalogsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_catalogs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5948,87 +5369,6 @@ def test_list_catalogs_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_catalogs_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_list_catalogs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.ListCatalogsRequest.pb( - catalog_service.ListCatalogsRequest() - ) - 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 = catalog_service.ListCatalogsResponse.to_json( - catalog_service.ListCatalogsResponse() - ) - - request = catalog_service.ListCatalogsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.ListCatalogsResponse() - - client.list_catalogs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_catalogs_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ListCatalogsRequest -): - client = CatalogServiceClient( - 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.list_catalogs(request) - - def test_list_catalogs_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6149,182 +5489,46 @@ def test_list_catalogs_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCatalogRequest, - dict, - ], -) -def test_update_catalog_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} - } - request_init["catalog"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3", - "display_name": "display_name_value", - "product_level_config": { - "ingestion_product_type": "ingestion_product_type_value", - "merchant_center_product_id_field": "merchant_center_product_id_field_value", - }, - "merchant_center_linking_config": { - "links": [ - { - "merchant_center_account_id": 2730, - "branch_id": "branch_id_value", - "destinations": ["destinations_value1", "destinations_value2"], - "region_code": "region_code_value", - "language_code": "language_code_value", - "feeds": [ - { - "primary_feed_id": 1571, - "primary_feed_name": "primary_feed_name_value", - } - ], - } - ] - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] + # Ensure method has been cached + assert client._transport.update_catalog in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_catalog] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.update_catalog(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.update_catalog(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["catalog"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["catalog"][field])): - del request_init["catalog"][field][i][subfield] - else: - del request_init["catalog"][field][subfield] - 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 = gcr_catalog.Catalog( - name="name_value", - display_name="display_name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_catalog.Catalog.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_catalog(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_catalog.Catalog) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - - -def test_update_catalog_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_catalog in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_catalog] = mock_rpc - - request = {} - client.update_catalog(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_catalog(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_catalog_rest_required_fields( - request_type=catalog_service.UpdateCatalogRequest, -): - transport_class = transports.CatalogServiceRestTransport +def test_update_catalog_rest_required_fields( + request_type=catalog_service.UpdateCatalogRequest, +): + transport_class = transports.CatalogServiceRestTransport request_init = {} request = request_type(**request_init) @@ -6402,87 +5606,6 @@ def test_update_catalog_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_catalog_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_catalog" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCatalogRequest.pb( - catalog_service.UpdateCatalogRequest() - ) - 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 = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) - - request = catalog_service.UpdateCatalogRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_catalog.Catalog() - - client.update_catalog( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_catalog_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCatalogRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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.update_catalog(request) - - def test_update_catalog_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6544,48 +5667,104 @@ def test_update_catalog_rest_flattened_error(transport: str = "rest"): ) -def test_update_catalog_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_set_default_branch_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.SetDefaultBranchRequest, - dict, - ], -) -def test_set_default_branch_rest(request_type): + # Ensure method has been cached + assert ( + client._transport.set_default_branch in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_default_branch + ] = mock_rpc + + request = {} + client.set_default_branch(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_default_branch(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None + # get arguments that satisfy an http rule for this method + sample_request = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + catalog="catalog_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_default_branch(request) - # Establish that the response is the type that we expect. - assert response is None + client.set_default_branch(**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/v2beta/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch" + % client.transport._host, + args[1], + ) -def test_set_default_branch_rest_use_cached_wrapped_rpc(): +def test_set_default_branch_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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.set_default_branch( + catalog_service.SetDefaultBranchRequest(), + catalog="catalog_value", + ) + + +def test_get_default_branch_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6600,7 +5779,7 @@ def test_set_default_branch_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.set_default_branch in client._transport._wrapped_methods + client._transport.get_default_branch in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6609,96 +5788,23 @@ def test_set_default_branch_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.set_default_branch + client._transport.get_default_branch ] = mock_rpc request = {} - client.set_default_branch(request) + client.get_default_branch(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_default_branch(request) + client.get_default_branch(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" - ) as pre: - pre.assert_not_called() - pb_message = catalog_service.SetDefaultBranchRequest.pb( - catalog_service.SetDefaultBranchRequest() - ) - 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() - - request = catalog_service.SetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.set_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_set_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.SetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.set_default_branch(request) - - -def test_set_default_branch_rest_flattened(): +def test_get_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6707,7 +5813,7 @@ def test_set_default_branch_rest_flattened(): # 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 = None + return_value = catalog_service.GetDefaultBranchResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -6723,24 +5829,26 @@ def test_set_default_branch_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.set_default_branch(**mock_args) + client.get_default_branch(**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/v2beta/{catalog=projects/*/locations/*/catalogs/*}:setDefaultBranch" + "%s/v2beta/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch" % client.transport._host, args[1], ) -def test_set_default_branch_rest_flattened_error(transport: str = "rest"): +def test_get_default_branch_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6749,61 +5857,13 @@ def test_set_default_branch_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.set_default_branch( - catalog_service.SetDefaultBranchRequest(), + client.get_default_branch( + catalog_service.GetDefaultBranchRequest(), catalog="catalog_value", ) -def test_set_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetDefaultBranchRequest, - dict, - ], -) -def test_get_default_branch_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( - branch="branch_value", - note="note_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_default_branch(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.GetDefaultBranchResponse) - assert response.branch == "branch_value" - assert response.note == "note_value" - - -def test_get_default_branch_rest_use_cached_wrapped_rpc(): +def test_get_completion_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6818,7 +5878,8 @@ def test_get_default_branch_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_default_branch in client._transport._wrapped_methods + client._transport.get_completion_config + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6827,200 +5888,126 @@ def test_get_default_branch_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_default_branch + client._transport.get_completion_config ] = mock_rpc request = {} - client.get_default_branch(request) + client.get_completion_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_default_branch(request) + client.get_completion_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_default_branch_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_default_branch" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetDefaultBranchRequest.pb( - catalog_service.GetDefaultBranchRequest() - ) - 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 = catalog_service.GetDefaultBranchResponse.to_json( - catalog_service.GetDefaultBranchResponse() - ) - - request = catalog_service.GetDefaultBranchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog_service.GetDefaultBranchResponse() +def test_get_completion_config_rest_required_fields( + request_type=catalog_service.GetCompletionConfigRequest, +): + transport_class = transports.CatalogServiceRestTransport - client.get_default_branch( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + 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, use_integers_for_enums=False) + ) - pre.assert_called_once() - post.assert_called_once() + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_completion_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_get_default_branch_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetDefaultBranchRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # verify required fields with default values are now present - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/sample3"} - request = request_type(**request_init) + jsonified_request["name"] = "name_value" - # 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_default_branch(request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_completion_config._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" -def test_get_default_branch_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = catalog.CompletionConfig() # 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 = catalog_service.GetDefaultBranchResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - catalog="catalog_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + 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 - client.get_default_branch(**mock_args) + response_value = Response() + response_value.status_code = 200 - # 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/v2beta/{catalog=projects/*/locations/*/catalogs/*}:getDefaultBranch" - % client.transport._host, - args[1], - ) + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_get_default_branch_rest_flattened_error(transport: str = "rest"): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + response = client.get_completion_config(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_default_branch( - catalog_service.GetDefaultBranchRequest(), - catalog="catalog_value", - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params -def test_get_default_branch_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_get_completion_config_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_completion_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetCompletionConfigRequest, - dict, - ], -) -def test_get_completion_config_rest(request_type): + +def test_get_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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 = catalog.CompletionConfig( + return_value = catalog.CompletionConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + + # get truthy value for each flattened field + mock_args = dict( name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -7028,33 +6015,38 @@ def test_get_completion_config_rest(request_type): # Convert return value to protobuf type return_value = catalog.CompletionConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_completion_config(request) - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" + client.get_completion_config(**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/v2beta/{name=projects/*/locations/*/catalogs/*/completionConfig}" + % client.transport._host, + args[1], + ) + + +def test_get_completion_config_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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_completion_config( + catalog_service.GetCompletionConfigRequest(), + name="name_value", + ) + -def test_get_completion_config_rest_use_cached_wrapped_rpc(): +def test_update_completion_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7069,7 +6061,7 @@ def test_get_completion_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_completion_config + client._transport.update_completion_config in client._transport._wrapped_methods ) @@ -7079,29 +6071,28 @@ def test_get_completion_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_completion_config + client._transport.update_completion_config ] = mock_rpc request = {} - client.get_completion_config(request) + client.update_completion_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_completion_config(request) + client.update_completion_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_completion_config_rest_required_fields( - request_type=catalog_service.GetCompletionConfigRequest, +def test_update_completion_config_rest_required_fields( + request_type=catalog_service.UpdateCompletionConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7112,21 +6103,19 @@ def test_get_completion_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_completion_config._get_unset_required_fields(jsonified_request) + ).update_completion_config._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_completion_config._get_unset_required_fields(jsonified_request) + ).update_completion_config._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7147,9 +6136,10 @@ def test_get_completion_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -7162,106 +6152,23 @@ def test_get_completion_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_completion_config(request) + response = client.update_completion_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_completion_config_rest_unset_required_fields(): +def test_update_completion_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_completion_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetCompletionConfigRequest.pb( - catalog_service.GetCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.GetCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.get_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - 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_completion_config(request) + unset_fields = transport.update_completion_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("completionConfig",))) -def test_get_completion_config_rest_flattened(): +def test_update_completion_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7274,12 +6181,15 @@ def test_get_completion_config_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + completion_config=catalog.CompletionConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -7292,20 +6202,20 @@ def test_get_completion_config_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_completion_config(**mock_args) + client.update_completion_config(**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/v2beta/{name=projects/*/locations/*/catalogs/*/completionConfig}" + "%s/v2beta/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}" % client.transport._host, args[1], ) -def test_get_completion_config_rest_flattened_error(transport: str = "rest"): +def test_update_completion_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7314,177 +6224,14 @@ def test_get_completion_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_completion_config( - catalog_service.GetCompletionConfigRequest(), - name="name_value", - ) - - -def test_get_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateCompletionConfigRequest, - dict, - ], -) -def test_update_completion_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - request_init["completion_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", - "matching_order": "matching_order_value", - "max_suggestions": 1632, - "min_prefix_length": 1810, - "auto_learning": True, - "suggestions_input_config": { - "big_query_source": { - "partition_date": {"year": 433, "month": 550, "day": 318}, - "project_id": "project_id_value", - "dataset_id": "dataset_id_value", - "table_id": "table_id_value", - "gcs_staging_dir": "gcs_staging_dir_value", - "data_schema": "data_schema_value", - } - }, - "last_suggestions_import_operation": "last_suggestions_import_operation_value", - "denylist_input_config": {}, - "last_denylist_import_operation": "last_denylist_import_operation_value", - "allowlist_input_config": {}, - "last_allowlist_import_operation": "last_allowlist_import_operation_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ - "completion_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["completion_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["completion_config"][field])): - del request_init["completion_config"][field][i][subfield] - else: - del request_init["completion_config"][field][subfield] - 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 = catalog.CompletionConfig( - name="name_value", - matching_order="matching_order_value", - max_suggestions=1632, - min_prefix_length=1810, - auto_learning=True, - last_suggestions_import_operation="last_suggestions_import_operation_value", - last_denylist_import_operation="last_denylist_import_operation_value", - last_allowlist_import_operation="last_allowlist_import_operation_value", + client.update_completion_config( + catalog_service.UpdateCompletionConfigRequest(), + completion_config=catalog.CompletionConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_completion_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.CompletionConfig) - assert response.name == "name_value" - assert response.matching_order == "matching_order_value" - assert response.max_suggestions == 1632 - assert response.min_prefix_length == 1810 - assert response.auto_learning is True - assert ( - response.last_suggestions_import_operation - == "last_suggestions_import_operation_value" - ) - assert ( - response.last_denylist_import_operation - == "last_denylist_import_operation_value" - ) - assert ( - response.last_allowlist_import_operation - == "last_allowlist_import_operation_value" - ) - -def test_update_completion_config_rest_use_cached_wrapped_rpc(): +def test_get_attributes_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7499,7 +6246,7 @@ def test_update_completion_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_completion_config + client._transport.get_attributes_config in client._transport._wrapped_methods ) @@ -7509,28 +6256,29 @@ def test_update_completion_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_completion_config + client._transport.get_attributes_config ] = mock_rpc request = {} - client.update_completion_config(request) + client.get_attributes_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_completion_config(request) + client.get_attributes_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_completion_config_rest_required_fields( - request_type=catalog_service.UpdateCompletionConfigRequest, +def test_get_attributes_config_rest_required_fields( + request_type=catalog_service.GetAttributesConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7541,19 +6289,21 @@ def test_update_completion_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_completion_config._get_unset_required_fields(jsonified_request) + ).get_attributes_config._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() - ).update_completion_config._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",)) + ).get_attributes_config._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 = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7562,7 +6312,7 @@ def test_update_completion_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = catalog.CompletionConfig() + return_value = catalog.AttributesConfig() # 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 @@ -7574,145 +6324,56 @@ def test_update_completion_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_completion_config(request) + response = client.get_attributes_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_completion_config_rest_unset_required_fields(): +def test_get_attributes_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_completion_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("completionConfig",))) + unset_fields = transport.get_attributes_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_completion_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_get_attributes_config_rest_flattened(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_completion_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateCompletionConfigRequest.pb( - catalog_service.UpdateCompletionConfigRequest() - ) - 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 = catalog.CompletionConfig.to_json( - catalog.CompletionConfig() - ) - - request = catalog_service.UpdateCompletionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.CompletionConfig() - - client.update_completion_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_completion_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateCompletionConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } - } - 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_completion_config(request) - - -def test_update_completion_config_rest_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = catalog.CompletionConfig() + return_value = catalog.AttributesConfig() # get arguments that satisfy an http rule for this method sample_request = { - "completion_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" - } + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" } # get truthy value for each flattened field mock_args = dict( - completion_config=catalog.CompletionConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -7720,25 +6381,25 @@ def test_update_completion_config_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.CompletionConfig.pb(return_value) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_completion_config(**mock_args) + client.get_attributes_config(**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/v2beta/{completion_config.name=projects/*/locations/*/catalogs/*/completionConfig}" + "%s/v2beta/{name=projects/*/locations/*/catalogs/*/attributesConfig}" % client.transport._host, args[1], ) -def test_update_completion_config_rest_flattened_error(transport: str = "rest"): +def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7747,67 +6408,13 @@ def test_update_completion_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_completion_config( - catalog_service.UpdateCompletionConfigRequest(), - completion_config=catalog.CompletionConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_completion_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.GetAttributesConfigRequest, - dict, - ], -) -def test_get_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( + client.get_attributes_config( + catalog_service.GetAttributesConfigRequest(), name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - -def test_get_attributes_config_rest_use_cached_wrapped_rpc(): +def test_update_attributes_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7822,7 +6429,7 @@ def test_get_attributes_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_attributes_config + client._transport.update_attributes_config in client._transport._wrapped_methods ) @@ -7832,29 +6439,28 @@ def test_get_attributes_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_attributes_config + client._transport.update_attributes_config ] = mock_rpc request = {} - client.get_attributes_config(request) + client.update_attributes_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attributes_config(request) + client.update_attributes_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_attributes_config_rest_required_fields( - request_type=catalog_service.GetAttributesConfigRequest, +def test_update_attributes_config_rest_required_fields( + request_type=catalog_service.UpdateAttributesConfigRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7865,21 +6471,19 @@ def test_get_attributes_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attributes_config._get_unset_required_fields(jsonified_request) + ).update_attributes_config._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_attributes_config._get_unset_required_fields(jsonified_request) + ).update_attributes_config._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 - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7900,9 +6504,10 @@ def test_get_attributes_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -7915,106 +6520,23 @@ def test_get_attributes_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_attributes_config(request) + response = client.update_attributes_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_attributes_config_rest_unset_required_fields(): +def test_update_attributes_config_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_attributes_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.GetAttributesConfigRequest.pb( - catalog_service.GetAttributesConfigRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.GetAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.get_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.GetAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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_attributes_config(request) + unset_fields = transport.update_attributes_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("attributesConfig",))) -def test_get_attributes_config_rest_flattened(): +def test_update_attributes_config_rest_flattened(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8027,12 +6549,15 @@ def test_get_attributes_config_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } } # get truthy value for each flattened field mock_args = dict( - name="name_value", + attributes_config=catalog.AttributesConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -8045,20 +6570,20 @@ def test_get_attributes_config_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_attributes_config(**mock_args) + client.update_attributes_config(**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/v2beta/{name=projects/*/locations/*/catalogs/*/attributesConfig}" + "%s/v2beta/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}" % client.transport._host, args[1], ) -def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): +def test_update_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8067,142 +6592,14 @@ def test_get_attributes_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_attributes_config( - catalog_service.GetAttributesConfigRequest(), - name="name_value", - ) - - -def test_get_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.UpdateAttributesConfigRequest, - dict, - ], -) -def test_update_attributes_config_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - request_init["attributes_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", - "catalog_attributes": {}, - "attribute_config_level": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ - "attributes_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["attributes_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["attributes_config"][field])): - del request_init["attributes_config"][field][i][subfield] - else: - del request_init["attributes_config"][field][subfield] - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + client.update_attributes_config( + catalog_service.UpdateAttributesConfigRequest(), + attributes_config=catalog.AttributesConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_attributes_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - -def test_update_attributes_config_rest_use_cached_wrapped_rpc(): +def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8217,7 +6614,7 @@ def test_update_attributes_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_attributes_config + client._transport.add_catalog_attribute in client._transport._wrapped_methods ) @@ -8227,28 +6624,29 @@ def test_update_attributes_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_attributes_config + client._transport.add_catalog_attribute ] = mock_rpc request = {} - client.update_attributes_config(request) + client.add_catalog_attribute(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_attributes_config(request) + client.add_catalog_attribute(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_attributes_config_rest_required_fields( - request_type=catalog_service.UpdateAttributesConfigRequest, +def test_add_catalog_attribute_rest_required_fields( + request_type=catalog_service.AddCatalogAttributeRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} + request_init["attributes_config"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8259,19 +6657,21 @@ def test_update_attributes_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attributes_config._get_unset_required_fields(jsonified_request) + ).add_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["attributesConfig"] = "attributes_config_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attributes_config._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",)) + ).add_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "attributesConfig" in jsonified_request + assert jsonified_request["attributesConfig"] == "attributes_config_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8292,7 +6692,7 @@ def test_update_attributes_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -8308,224 +6708,168 @@ def test_update_attributes_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_attributes_config(request) + response = client.add_catalog_attribute(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_attributes_config_rest_unset_required_fields(): +def test_add_catalog_attribute_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_attributes_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("attributesConfig",))) + unset_fields = transport.add_catalog_attribute._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "attributesConfig", + "catalogAttribute", + ) + ) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_attributes_config_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.UpdateAttributesConfigRequest.pb( - catalog_service.UpdateAttributesConfigRequest() +def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - request = catalog_service.UpdateAttributesConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() + # Ensure method has been cached + assert ( + client._transport.remove_catalog_attribute + in client._transport._wrapped_methods + ) - client.update_attributes_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.remove_catalog_attribute + ] = mock_rpc - pre.assert_called_once() - post.assert_called_once() + request = {} + client.remove_catalog_attribute(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_update_attributes_config_rest_bad_request( - transport: str = "rest", request_type=catalog_service.UpdateAttributesConfigRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.remove_catalog_attribute(request) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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_attributes_config(request) +def test_remove_catalog_attribute_rest_required_fields( + request_type=catalog_service.RemoveCatalogAttributeRequest, +): + transport_class = transports.CatalogServiceRestTransport -def test_update_attributes_config_rest_flattened(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + request_init = {} + request_init["attributes_config"] = "" + request_init["key"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # 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 = catalog.AttributesConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "attributes_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - } + # verify fields with default values are dropped - # get truthy value for each flattened field - mock_args = dict( - attributes_config=catalog.AttributesConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # verify required fields with default values are now present - client.update_attributes_config(**mock_args) + jsonified_request["attributesConfig"] = "attributes_config_value" + jsonified_request["key"] = "key_value" - # 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/v2beta/{attributes_config.name=projects/*/locations/*/catalogs/*/attributesConfig}" - % client.transport._host, - args[1], - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "attributesConfig" in jsonified_request + assert jsonified_request["attributesConfig"] == "attributes_config_value" + assert "key" in jsonified_request + assert jsonified_request["key"] == "key_value" -def test_update_attributes_config_rest_flattened_error(transport: str = "rest"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_attributes_config( - catalog_service.UpdateAttributesConfigRequest(), - attributes_config=catalog.AttributesConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - + # Designate an appropriate value for the returned response. + return_value = catalog.AttributesConfig() + # 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 -def test_update_attributes_config_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.AddCatalogAttributeRequest, - dict, - ], -) -def test_add_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - request = request_type(**request_init) + response = client.remove_catalog_attribute(request) - # 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_catalog_attribute(request) +def test_remove_catalog_attribute_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + unset_fields = transport.remove_catalog_attribute._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "attributesConfig", + "key", + ) + ) ) -def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): +def test_batch_remove_catalog_attributes_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8540,7 +6884,7 @@ def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.add_catalog_attribute + client._transport.batch_remove_catalog_attributes in client._transport._wrapped_methods ) @@ -8550,29 +6894,30 @@ def test_add_catalog_attribute_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.add_catalog_attribute + client._transport.batch_remove_catalog_attributes ] = mock_rpc request = {} - client.add_catalog_attribute(request) + client.batch_remove_catalog_attributes(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.add_catalog_attribute(request) + client.batch_remove_catalog_attributes(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_add_catalog_attribute_rest_required_fields( - request_type=catalog_service.AddCatalogAttributeRequest, +def test_batch_remove_catalog_attributes_rest_required_fields( + request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} request_init["attributes_config"] = "" + request_init["attribute_keys"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8583,21 +6928,24 @@ def test_add_catalog_attribute_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).add_catalog_attribute._get_unset_required_fields(jsonified_request) + ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["attributesConfig"] = "attributes_config_value" + jsonified_request["attributeKeys"] = "attribute_keys_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).add_catalog_attribute._get_unset_required_fields(jsonified_request) + ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "attributesConfig" in jsonified_request assert jsonified_request["attributesConfig"] == "attributes_config_value" + assert "attributeKeys" in jsonified_request + assert jsonified_request["attributeKeys"] == "attribute_keys_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8606,7 +6954,7 @@ def test_add_catalog_attribute_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = catalog.AttributesConfig() + return_value = catalog_service.BatchRemoveCatalogAttributesResponse() # 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 @@ -8628,179 +6976,47 @@ def test_add_catalog_attribute_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.add_catalog_attribute(request) + response = client.batch_remove_catalog_attributes(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_add_catalog_attribute_rest_unset_required_fields(): +def test_batch_remove_catalog_attributes_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.add_catalog_attribute._get_unset_required_fields({}) + unset_fields = transport.batch_remove_catalog_attributes._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set(()) & set( ( "attributesConfig", - "catalogAttribute", + "attributeKeys", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), - ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_add_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.AddCatalogAttributeRequest.pb( - catalog_service.AddCatalogAttributeRequest() - ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) - - request = catalog_service.AddCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.add_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.AddCatalogAttributeRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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.add_catalog_attribute(request) - - -def test_add_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - catalog_service.RemoveCatalogAttributeRequest, - dict, - ], -) -def test_remove_catalog_attribute_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_catalog_attribute(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - - -def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_replace_catalog_attribute_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -8809,7 +7025,7 @@ def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.remove_catalog_attribute + client._transport.replace_catalog_attribute in client._transport._wrapped_methods ) @@ -8819,30 +7035,29 @@ def test_remove_catalog_attribute_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.remove_catalog_attribute + client._transport.replace_catalog_attribute ] = mock_rpc request = {} - client.remove_catalog_attribute(request) + client.replace_catalog_attribute(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.remove_catalog_attribute(request) + client.replace_catalog_attribute(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_remove_catalog_attribute_rest_required_fields( - request_type=catalog_service.RemoveCatalogAttributeRequest, +def test_replace_catalog_attribute_rest_required_fields( + request_type=catalog_service.ReplaceCatalogAttributeRequest, ): transport_class = transports.CatalogServiceRestTransport request_init = {} request_init["attributes_config"] = "" - request_init["key"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8853,24 +7068,21 @@ def test_remove_catalog_attribute_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["attributesConfig"] = "attributes_config_value" - jsonified_request["key"] = "key_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).remove_catalog_attribute._get_unset_required_fields(jsonified_request) + ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "attributesConfig" in jsonified_request assert jsonified_request["attributesConfig"] == "attributes_config_value" - assert "key" in jsonified_request - assert jsonified_request["key"] == "key_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8907,130 +7119,2115 @@ def test_remove_catalog_attribute_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_catalog_attribute(request) + response = client.replace_catalog_attribute(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_remove_catalog_attribute_rest_unset_required_fields(): +def test_replace_catalog_attribute_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.remove_catalog_attribute._get_unset_required_fields({}) + unset_fields = transport.replace_catalog_attribute._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "attributesConfig", - "key", + "catalogAttribute", ) ) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_catalog_attribute_rest_interceptors(null_interceptor): - transport = transports.CatalogServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CatalogServiceRestInterceptor(), ) - client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" - ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( - catalog_service.RemoveCatalogAttributeRequest() + with pytest.raises(ValueError): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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 = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() + # It is an error to provide a credentials file and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - request = catalog_service.RemoveCatalogAttributeRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = catalog.AttributesConfig() - - client.remove_catalog_attribute( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, + transport=transport, ) - pre.assert_called_once() - post.assert_called_once() - + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) -def test_remove_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.RemoveCatalogAttributeRequest -): - client = CatalogServiceClient( + # It is an error to provide scopes and a transport instance. + transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) - # send a request that will satisfy transcoding - request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" - } - 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.remove_catalog_attribute(request) +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CatalogServiceClient(transport=transport) + assert client.transport is transport -def test_remove_catalog_attribute_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), ) + channel = transport.grpc_channel + assert channel + + transport = transports.CatalogServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + transports.CatalogServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CatalogServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + call.return_value = catalog_service.ListCatalogsResponse() + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + call.return_value = gcr_catalog.Catalog() + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + call.return_value = None + client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + call.return_value = catalog_service.GetDefaultBranchResponse() + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + call.return_value = catalog.CompletionConfig() + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_remove_catalog_attributes_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + call.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() + client.batch_remove_catalog_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + call.return_value = catalog.AttributesConfig() + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CatalogServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_catalogs_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_catalog_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + ) + await client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.set_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_default_branch_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + ) + await client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_completion_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + ) + await client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_attributes_config_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.update_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_remove_catalog_attributes_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog_service.BatchRemoveCatalogAttributesResponse( + deleted_catalog_attributes=["deleted_catalog_attributes_value"], + reset_catalog_attributes=["reset_catalog_attributes_value"], + ) + ) + await client.batch_remove_catalog_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_replace_catalog_attribute_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + ) + await client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CatalogServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_catalogs_rest_bad_request( + request_type=catalog_service.ListCatalogsRequest, +): + client = CatalogServiceClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_catalogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ListCatalogsRequest, + dict, + ], +) +def test_list_catalogs_rest_call_success(request_type): + client = CatalogServiceClient( + 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 = catalog_service.ListCatalogsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.ListCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_catalogs_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_list_catalogs" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_list_catalogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ListCatalogsRequest.pb( + catalog_service.ListCatalogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.ListCatalogsResponse.to_json( + catalog_service.ListCatalogsResponse() + ) + req.return_value.content = return_value + + request = catalog_service.ListCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.ListCatalogsResponse() + + client.list_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_catalog_rest_bad_request( + request_type=catalog_service.UpdateCatalogRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCatalogRequest, + dict, + ], +) +def test_update_catalog_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "catalog": {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + } + request_init["catalog"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3", + "display_name": "display_name_value", + "product_level_config": { + "ingestion_product_type": "ingestion_product_type_value", + "merchant_center_product_id_field": "merchant_center_product_id_field_value", + }, + "merchant_center_linking_config": { + "links": [ + { + "merchant_center_account_id": 2730, + "branch_id": "branch_id_value", + "destinations": ["destinations_value1", "destinations_value2"], + "region_code": "region_code_value", + "language_code": "language_code_value", + "feeds": [ + { + "primary_feed_id": 1571, + "primary_feed_name": "primary_feed_name_value", + } + ], + } + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCatalogRequest.meta.fields["catalog"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["catalog"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["catalog"][field])): + del request_init["catalog"][field][i][subfield] + else: + del request_init["catalog"][field][subfield] + 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 = gcr_catalog.Catalog( + name="name_value", + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_catalog.Catalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_catalog.Catalog) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_catalog_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_catalog" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_catalog" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCatalogRequest.pb( + catalog_service.UpdateCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_catalog.Catalog.to_json(gcr_catalog.Catalog()) + req.return_value.content = return_value + + request = catalog_service.UpdateCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_catalog.Catalog() + + client.update_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_default_branch_rest_bad_request( + request_type=catalog_service.SetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.SetDefaultBranchRequest, + dict, + ], +) +def test_set_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_default_branch(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "pre_set_default_branch" + ) as pre: + pre.assert_not_called() + pb_message = catalog_service.SetDefaultBranchRequest.pb( + catalog_service.SetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = catalog_service.SetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.set_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_default_branch_rest_bad_request( + request_type=catalog_service.GetDefaultBranchRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_default_branch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetDefaultBranchRequest, + dict, + ], +) +def test_get_default_branch_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = catalog_service.GetDefaultBranchResponse( + branch="branch_value", + note="note_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog_service.GetDefaultBranchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_default_branch(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog_service.GetDefaultBranchResponse) + assert response.branch == "branch_value" + assert response.note == "note_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_default_branch_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_default_branch" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_default_branch" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetDefaultBranchRequest.pb( + catalog_service.GetDefaultBranchRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.GetDefaultBranchResponse.to_json( + catalog_service.GetDefaultBranchResponse() + ) + req.return_value.content = return_value + + request = catalog_service.GetDefaultBranchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.GetDefaultBranchResponse() + + client.get_default_branch( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_completion_config_rest_bad_request( + request_type=catalog_service.GetCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetCompletionConfigRequest, + dict, + ], +) +def test_get_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetCompletionConfigRequest.pb( + catalog_service.GetCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.GetCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.get_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_completion_config_rest_bad_request( + request_type=catalog_service.UpdateCompletionConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_completion_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateCompletionConfigRequest, + dict, + ], +) +def test_update_completion_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "completion_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig" + } + } + request_init["completion_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/completionConfig", + "matching_order": "matching_order_value", + "max_suggestions": 1632, + "min_prefix_length": 1810, + "auto_learning": True, + "suggestions_input_config": { + "big_query_source": { + "partition_date": {"year": 433, "month": 550, "day": 318}, + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "table_id": "table_id_value", + "gcs_staging_dir": "gcs_staging_dir_value", + "data_schema": "data_schema_value", + } + }, + "last_suggestions_import_operation": "last_suggestions_import_operation_value", + "denylist_input_config": {}, + "last_denylist_import_operation": "last_denylist_import_operation_value", + "allowlist_input_config": {}, + "last_allowlist_import_operation": "last_allowlist_import_operation_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateCompletionConfigRequest.meta.fields[ + "completion_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["completion_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["completion_config"][field])): + del request_init["completion_config"][field][i][subfield] + else: + del request_init["completion_config"][field][subfield] + 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 = catalog.CompletionConfig( + name="name_value", + matching_order="matching_order_value", + max_suggestions=1632, + min_prefix_length=1810, + auto_learning=True, + last_suggestions_import_operation="last_suggestions_import_operation_value", + last_denylist_import_operation="last_denylist_import_operation_value", + last_allowlist_import_operation="last_allowlist_import_operation_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.CompletionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_completion_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CompletionConfig) + assert response.name == "name_value" + assert response.matching_order == "matching_order_value" + assert response.max_suggestions == 1632 + assert response.min_prefix_length == 1810 + assert response.auto_learning is True + assert ( + response.last_suggestions_import_operation + == "last_suggestions_import_operation_value" + ) + assert ( + response.last_denylist_import_operation + == "last_denylist_import_operation_value" + ) + assert ( + response.last_allowlist_import_operation + == "last_allowlist_import_operation_value" + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_completion_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_completion_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_completion_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCompletionConfigRequest.pb( + catalog_service.UpdateCompletionConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.CompletionConfig.to_json(catalog.CompletionConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateCompletionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CompletionConfig() + + client.update_completion_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attributes_config_rest_bad_request( + request_type=catalog_service.GetAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.GetAttributesConfigRequest, + dict, + ], +) +def test_get_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_get_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_get_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetAttributesConfigRequest.pb( + catalog_service.GetAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.GetAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.get_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attributes_config_rest_bad_request( + request_type=catalog_service.UpdateAttributesConfigRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_attributes_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.UpdateAttributesConfigRequest, + dict, + ], +) +def test_update_attributes_config_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "attributes_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + } + request_init["attributes_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig", + "catalog_attributes": {}, + "attribute_config_level": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = catalog_service.UpdateAttributesConfigRequest.meta.fields[ + "attributes_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["attributes_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["attributes_config"][field])): + del request_init["attributes_config"][field][i][subfield] + else: + del request_init["attributes_config"][field][subfield] + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_attributes_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attributes_config_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_update_attributes_config" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_update_attributes_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateAttributesConfigRequest.pb( + catalog_service.UpdateAttributesConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value + + request = catalog_service.UpdateAttributesConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() + + client.update_attributes_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_catalog_attribute_rest_bad_request( + request_type=catalog_service.AddCatalogAttributeRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_catalog_attribute(request) + - @pytest.mark.parametrize( "request_type", [ - catalog_service.BatchRemoveCatalogAttributesRequest, + catalog_service.AddCatalogAttributeRequest, dict, ], ) -def test_batch_remove_catalog_attributes_rest(request_type): +def test_add_catalog_attribute_rest_call_success(request_type): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9042,173 +9239,161 @@ def test_batch_remove_catalog_attributes_rest(request_type): # 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 = catalog_service.BatchRemoveCatalogAttributesResponse( - deleted_catalog_attributes=["deleted_catalog_attributes_value"], - reset_catalog_attributes=["reset_catalog_attributes_value"], + return_value = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( - return_value - ) + return_value = catalog.AttributesConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_remove_catalog_attributes(request) + response = client.add_catalog_attribute(request) # Establish that the response is the type that we expect. - assert isinstance(response, catalog_service.BatchRemoveCatalogAttributesResponse) - assert response.deleted_catalog_attributes == ["deleted_catalog_attributes_value"] - assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] - - -def test_batch_remove_catalog_attributes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.batch_remove_catalog_attributes - in client._transport._wrapped_methods - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_catalog_attribute_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CatalogServiceRestInterceptor, "post_add_catalog_attribute" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_add_catalog_attribute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.AddCatalogAttributeRequest.pb( + catalog_service.AddCatalogAttributeRequest() ) - client._transport._wrapped_methods[ - client._transport.batch_remove_catalog_attributes - ] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.batch_remove_catalog_attributes(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = catalog_service.AddCatalogAttributeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.AttributesConfig() - client.batch_remove_catalog_attributes(request) + client.add_catalog_attribute( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_batch_remove_catalog_attributes_rest_required_fields( - request_type=catalog_service.BatchRemoveCatalogAttributesRequest, +def test_remove_catalog_attribute_rest_bad_request( + request_type=catalog_service.RemoveCatalogAttributeRequest, ): - transport_class = transports.CatalogServiceRestTransport - - request_init = {} - request_init["attributes_config"] = "" - request_init["attribute_keys"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["attributesConfig"] = "attributes_config_value" - jsonified_request["attributeKeys"] = "attribute_keys_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).batch_remove_catalog_attributes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "attributesConfig" in jsonified_request - assert jsonified_request["attributesConfig"] == "attributes_config_value" - assert "attributeKeys" in jsonified_request - assert jsonified_request["attributeKeys"] == "attribute_keys_value" - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = catalog_service.BatchRemoveCatalogAttributesResponse() - # 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 - - # Convert return value to protobuf type - return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.batch_remove_catalog_attributes(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_catalog_attribute(request) -def test_batch_remove_catalog_attributes_rest_unset_required_fields(): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.RemoveCatalogAttributeRequest, + dict, + ], +) +def test_remove_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - unset_fields = transport.batch_remove_catalog_attributes._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "attributesConfig", - "attributeKeys", - ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): +def test_remove_catalog_attribute_rest_interceptors(null_interceptor): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9216,19 +9401,20 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): else transports.CatalogServiceRestInterceptor(), ) client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_batch_remove_catalog_attributes" + transports.CatalogServiceRestInterceptor, "post_remove_catalog_attribute" ) as post, mock.patch.object( - transports.CatalogServiceRestInterceptor, "pre_batch_remove_catalog_attributes" + transports.CatalogServiceRestInterceptor, "pre_remove_catalog_attribute" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = catalog_service.BatchRemoveCatalogAttributesRequest.pb( - catalog_service.BatchRemoveCatalogAttributesRequest() + pb_message = catalog_service.RemoveCatalogAttributeRequest.pb( + catalog_service.RemoveCatalogAttributeRequest() ) transcode.return_value = { "method": "post", @@ -9237,24 +9423,20 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - catalog_service.BatchRemoveCatalogAttributesResponse.to_json( - catalog_service.BatchRemoveCatalogAttributesResponse() - ) - ) + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value - request = catalog_service.BatchRemoveCatalogAttributesRequest() + request = catalog_service.RemoveCatalogAttributeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() + post.return_value = catalog.AttributesConfig() - client.batch_remove_catalog_attributes( + client.remove_catalog_attribute( request, metadata=[ ("key", "val"), @@ -9267,14 +9449,11 @@ def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): def test_batch_remove_catalog_attributes_rest_bad_request( - transport: str = "rest", request_type=catalog_service.BatchRemoveCatalogAttributesRequest, ): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" @@ -9286,30 +9465,25 @@ def test_batch_remove_catalog_attributes_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.batch_remove_catalog_attributes(request) -def test_batch_remove_catalog_attributes_rest_error(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - catalog_service.ReplaceCatalogAttributeRequest, + catalog_service.BatchRemoveCatalogAttributesRequest, dict, ], ) -def test_replace_catalog_attribute_rest(request_type): +def test_batch_remove_catalog_attributes_rest_call_success(request_type): client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -9321,161 +9495,157 @@ def test_replace_catalog_attribute_rest(request_type): # 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 = catalog.AttributesConfig( - name="name_value", - attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + return_value = catalog_service.BatchRemoveCatalogAttributesResponse( + deleted_catalog_attributes=["deleted_catalog_attributes_value"], + reset_catalog_attributes=["reset_catalog_attributes_value"], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.replace_catalog_attribute(request) + response = client.batch_remove_catalog_attributes(request) # Establish that the response is the type that we expect. - assert isinstance(response, catalog.AttributesConfig) - assert response.name == "name_value" - assert ( - response.attribute_config_level - == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG - ) - + assert isinstance(response, catalog_service.BatchRemoveCatalogAttributesResponse) + assert response.deleted_catalog_attributes == ["deleted_catalog_attributes_value"] + assert response.reset_catalog_attributes == ["reset_catalog_attributes_value"] -def test_replace_catalog_attribute_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_remove_catalog_attributes_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) - # Ensure method has been cached - assert ( - client._transport.replace_catalog_attribute - in client._transport._wrapped_methods + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CatalogServiceRestInterceptor, "post_batch_remove_catalog_attributes" + ) as post, mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_batch_remove_catalog_attributes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.BatchRemoveCatalogAttributesRequest.pb( + catalog_service.BatchRemoveCatalogAttributesRequest() ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = catalog_service.BatchRemoveCatalogAttributesResponse.to_json( + catalog_service.BatchRemoveCatalogAttributesResponse() ) - client._transport._wrapped_methods[ - client._transport.replace_catalog_attribute - ] = mock_rpc - - request = {} - client.replace_catalog_attribute(request) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = catalog_service.BatchRemoveCatalogAttributesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.BatchRemoveCatalogAttributesResponse() - client.replace_catalog_attribute(request) + client.batch_remove_catalog_attributes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_replace_catalog_attribute_rest_required_fields( +def test_replace_catalog_attribute_rest_bad_request( request_type=catalog_service.ReplaceCatalogAttributeRequest, ): - transport_class = transports.CatalogServiceRestTransport - - request_init = {} - request_init["attributes_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["attributesConfig"] = "attributes_config_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).replace_catalog_attribute._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "attributesConfig" in jsonified_request - assert jsonified_request["attributesConfig"] == "attributes_config_value" - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = catalog.AttributesConfig() - # 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 - - # Convert return value to protobuf type - return_value = catalog.AttributesConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.replace_catalog_attribute(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.replace_catalog_attribute(request) +@pytest.mark.parametrize( + "request_type", + [ + catalog_service.ReplaceCatalogAttributeRequest, + dict, + ], +) +def test_replace_catalog_attribute_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = { + "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + } + 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 = catalog.AttributesConfig( + name="name_value", + attribute_config_level=common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG, + ) -def test_replace_catalog_attribute_rest_unset_required_fields(): - transport = transports.CatalogServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.replace_catalog_attribute._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "attributesConfig", - "catalogAttribute", - ) - ) + # Convert return value to protobuf type + return_value = catalog.AttributesConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.replace_catalog_attribute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.AttributesConfig) + assert response.name == "name_value" + assert ( + response.attribute_config_level + == common.AttributeConfigLevel.PRODUCT_LEVEL_ATTRIBUTE_CONFIG ) @@ -9488,6 +9658,7 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): else transports.CatalogServiceRestInterceptor(), ) client = CatalogServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -9509,12 +9680,10 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = catalog.AttributesConfig.to_json( - catalog.AttributesConfig() - ) + return_value = catalog.AttributesConfig.to_json(catalog.AttributesConfig()) + req.return_value.content = return_value request = catalog_service.ReplaceCatalogAttributeRequest() metadata = [ @@ -9536,19 +9705,82 @@ def test_replace_catalog_attribute_rest_interceptors(null_interceptor): post.assert_called_once() -def test_replace_catalog_attribute_rest_bad_request( - transport: str = "rest", request_type=catalog_service.ReplaceCatalogAttributeRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding request_init = { - "attributes_config": "projects/sample1/locations/sample2/catalogs/sample3/attributesConfig" + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" } request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -9556,122 +9788,313 @@ def test_replace_catalog_attribute_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.replace_catalog_attribute(request) + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_replace_catalog_attribute_rest_error(): +def test_initialize_client_w_rest(): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CatalogServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_catalogs_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_catalogs), "__call__") as call: + client.list_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ListCatalogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_catalog_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_catalog), "__call__") as call: + client.update_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCatalogRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_default_branch_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.set_default_branch), "__call__" + ) as call: + client.set_default_branch(request=None) - # It is an error to provide scopes and a transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.SetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_default_branch_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_branch), "__call__" + ) as call: + client.get_default_branch(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetDefaultBranchRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_completion_config), "__call__" + ) as call: + client.get_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_completion_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_completion_config), "__call__" + ) as call: + client.update_completion_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateCompletionConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_attributes_config_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_attributes_config), "__call__" + ) as call: + client.get_attributes_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.GetAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_attributes_config_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CatalogServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_attributes_config), "__call__" + ) as call: + client.update_attributes_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.UpdateAttributesConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CatalogServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_catalog_attribute), "__call__" + ) as call: + client.add_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.AddCatalogAttributeRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CatalogServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CatalogServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_catalog_attribute), "__call__" + ) as call: + client.remove_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.RemoveCatalogAttributeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_remove_catalog_attributes_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_remove_catalog_attributes), "__call__" + ) as call: + client.batch_remove_catalog_attributes(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CatalogServiceGrpcTransport, - transports.CatalogServiceGrpcAsyncIOTransport, - transports.CatalogServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.BatchRemoveCatalogAttributesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CatalogServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_replace_catalog_attribute_empty_call_rest(): + client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.replace_catalog_attribute), "__call__" + ) as call: + client.replace_catalog_attribute(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog_service.ReplaceCatalogAttributeRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -10376,141 +10799,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10538,7 +10826,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10593,7 +10881,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10640,7 +10928,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -10683,7 +10971,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -10738,7 +11026,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -10785,7 +11073,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CatalogServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -10801,22 +11089,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_completion_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_completion_service.py index ff5a37bfc789..405c048407d2 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_completion_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_completion_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -45,15 +62,7 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.type import date_pb2 # type: ignore -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.retail_v2beta.services.completion_service import ( CompletionServiceAsyncClient, @@ -63,10 +72,24 @@ from google.cloud.retail_v2beta.types import completion_service, import_config +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1202,25 +1225,6 @@ def test_complete_query(request_type, transport: str = "grpc"): assert response.attribution_token == "attribution_token_value" -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - def test_complete_query_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1294,29 +1298,6 @@ def test_complete_query_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_complete_query_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.complete_query), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - ) - response = await client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - @pytest.mark.asyncio async def test_complete_query_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1325,7 +1306,7 @@ async def test_complete_query_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1365,7 +1346,7 @@ async def test_complete_query_async( request_type=completion_service.CompleteQueryRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1431,7 +1412,7 @@ def test_complete_query_field_headers(): @pytest.mark.asyncio async def test_complete_query_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1495,27 +1476,6 @@ def test_import_completion_data(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_completion_data_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - def test_import_completion_data_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1593,29 +1553,6 @@ def test_import_completion_data_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_completion_data_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_completion_data), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_completion_data() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportCompletionDataRequest() - - @pytest.mark.asyncio async def test_import_completion_data_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1624,7 +1561,7 @@ async def test_import_completion_data_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1669,7 +1606,7 @@ async def test_import_completion_data_async( request_type=import_config.ImportCompletionDataRequest, ): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1736,7 +1673,7 @@ def test_import_completion_data_field_headers(): @pytest.mark.asyncio async def test_import_completion_data_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1767,46 +1704,6 @@ async def test_import_completion_data_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - completion_service.CompleteQueryRequest, - dict, - ], -) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( - attribution_token="attribution_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.attribution_token == "attribution_token_value" - - def test_complete_query_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1971,128 +1868,6 @@ def test_complete_query_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" - ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, "pre_complete_query" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb( - completion_service.CompleteQueryRequest() - ) - 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 = completion_service.CompleteQueryResponse.to_json( - completion_service.CompleteQueryResponse() - ) - - request = completion_service.CompleteQueryRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request( - transport: str = "rest", request_type=completion_service.CompleteQueryRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportCompletionDataRequest, - dict, - ], -) -def test_import_completion_data_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_completion_data(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_completion_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2227,15 +2002,419 @@ def test_import_completion_data_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_completion_data_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = CompletionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CompletionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_complete_query_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + ) + await client.complete_query(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_completion_data_empty_call_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_completion_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CompletionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_complete_query_rest_bad_request( + request_type=completion_service.CompleteQueryRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.complete_query(request) + + +@pytest.mark.parametrize( + "request_type", + [ + completion_service.CompleteQueryRequest, + dict, + ], +) +def test_complete_query_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = completion_service.CompleteQueryResponse( + attribution_token="attribution_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.attribution_token == "attribution_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_complete_query" + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, "pre_complete_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb( + completion_service.CompleteQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = completion_service.CompleteQueryResponse.to_json( + completion_service.CompleteQueryResponse() + ) + req.return_value.content = return_value + + request = completion_service.CompleteQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_completion_data_rest_bad_request( + request_type=import_config.ImportCompletionDataRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_completion_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportCompletionDataRequest, + dict, + ], +) +def test_import_completion_data_rest_call_success(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_completion_data(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_completion_data_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), ) client = CompletionServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -2259,12 +2438,10 @@ def test_import_completion_data_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = import_config.ImportCompletionDataRequest() metadata = [ @@ -2286,17 +2463,20 @@ def test_import_completion_data_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_completion_data_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportCompletionDataRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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( @@ -2304,122 +2484,174 @@ def test_import_completion_data_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.import_completion_data(request) + client.get_operation(request) -def test_import_completion_data_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +def test_initialize_client_w_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + assert client is not None -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_complete_query_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.complete_query), "__call__") as call: + client.complete_query(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = completion_service.CompleteQueryRequest() - transport = transports.CompletionServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_completion_data_empty_call_rest(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_data), "__call__" + ) as call: + client.import_completion_data(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportCompletionDataRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( + +def test_completion_service_rest_lro_client(): + client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -2659,23 +2891,6 @@ def test_completion_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_completion_service_rest_lro_client(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -3059,141 +3274,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3221,7 +3301,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3276,7 +3356,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3323,7 +3403,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3366,7 +3446,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3421,7 +3501,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3468,7 +3548,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3484,22 +3564,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = CompletionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_control_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_control_service.py index 61304c7c2765..8f68c1dc82c6 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_control_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_control_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,15 +54,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2beta.services.control_service import ( ControlServiceAsyncClient, @@ -59,10 +68,24 @@ from google.cloud.retail_v2beta.types import control_service, search_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1174,25 +1197,6 @@ def test_create_control(request_type, transport: str = "grpc"): ] -def test_create_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - def test_create_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1258,35 +1262,6 @@ def test_create_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.create_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.CreateControlRequest() - - @pytest.mark.asyncio async def test_create_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1295,7 +1270,7 @@ async def test_create_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1334,7 +1309,7 @@ async def test_create_control_async( transport: str = "grpc_asyncio", request_type=control_service.CreateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1414,7 +1389,7 @@ def test_create_control_field_headers(): @pytest.mark.asyncio async def test_create_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1510,7 +1485,7 @@ def test_create_control_flattened_error(): @pytest.mark.asyncio async def test_create_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1557,7 +1532,7 @@ async def test_create_control_flattened_async(): @pytest.mark.asyncio async def test_create_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1610,25 +1585,6 @@ def test_delete_control(request_type, transport: str = "grpc"): assert response is None -def test_delete_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - def test_delete_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1692,25 +1648,6 @@ def test_delete_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.DeleteControlRequest() - - @pytest.mark.asyncio async def test_delete_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1719,7 +1656,7 @@ async def test_delete_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1758,7 +1695,7 @@ async def test_delete_control_async( transport: str = "grpc_asyncio", request_type=control_service.DeleteControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1819,7 +1756,7 @@ def test_delete_control_field_headers(): @pytest.mark.asyncio async def test_delete_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1887,7 +1824,7 @@ def test_delete_control_flattened_error(): @pytest.mark.asyncio async def test_delete_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1914,7 +1851,7 @@ async def test_delete_control_flattened_async(): @pytest.mark.asyncio async def test_delete_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1976,25 +1913,6 @@ def test_update_control(request_type, transport: str = "grpc"): ] -def test_update_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - def test_update_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2054,35 +1972,6 @@ def test_update_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.update_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.UpdateControlRequest() - - @pytest.mark.asyncio async def test_update_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2091,7 +1980,7 @@ async def test_update_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2130,7 +2019,7 @@ async def test_update_control_async( transport: str = "grpc_asyncio", request_type=control_service.UpdateControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2210,7 +2099,7 @@ def test_update_control_field_headers(): @pytest.mark.asyncio async def test_update_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2301,7 +2190,7 @@ def test_update_control_flattened_error(): @pytest.mark.asyncio async def test_update_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2344,7 +2233,7 @@ async def test_update_control_flattened_async(): @pytest.mark.asyncio async def test_update_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2413,25 +2302,6 @@ def test_get_control(request_type, transport: str = "grpc"): ] -def test_get_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - def test_get_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2495,35 +2365,6 @@ def test_get_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - ) - response = await client.get_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.GetControlRequest() - - @pytest.mark.asyncio async def test_get_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2532,7 +2373,7 @@ async def test_get_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2571,7 +2412,7 @@ async def test_get_control_async( transport: str = "grpc_asyncio", request_type=control_service.GetControlRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2651,7 +2492,7 @@ def test_get_control_field_headers(): @pytest.mark.asyncio async def test_get_control_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2719,7 +2560,7 @@ def test_get_control_flattened_error(): @pytest.mark.asyncio async def test_get_control_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2746,7 +2587,7 @@ async def test_get_control_flattened_async(): @pytest.mark.asyncio async def test_get_control_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2794,25 +2635,6 @@ def test_list_controls(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_controls_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - def test_list_controls_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2880,29 +2702,6 @@ def test_list_controls_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_controls_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_controls), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - control_service.ListControlsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_controls() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == control_service.ListControlsRequest() - - @pytest.mark.asyncio async def test_list_controls_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2911,7 +2710,7 @@ async def test_list_controls_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2950,7 +2749,7 @@ async def test_list_controls_async( transport: str = "grpc_asyncio", request_type=control_service.ListControlsRequest ): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3016,7 +2815,7 @@ def test_list_controls_field_headers(): @pytest.mark.asyncio async def test_list_controls_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3086,7 +2885,7 @@ def test_list_controls_flattened_error(): @pytest.mark.asyncio async def test_list_controls_flattened_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3115,7 +2914,7 @@ async def test_list_controls_flattened_async(): @pytest.mark.asyncio async def test_list_controls_flattened_error_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3225,7 +3024,7 @@ def test_list_controls_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_controls_async_pager(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3275,7 +3074,7 @@ async def test_list_controls_async_pager(): @pytest.mark.asyncio async def test_list_controls_async_pages(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3321,221 +3120,14 @@ async def test_list_controls_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - control_service.CreateControlRequest, - dict, - ], -) -def test_create_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["control"] = { - "facet_spec": { - "facet_key": { - "key": "key_value", - "intervals": [ - { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - } - ], - "restricted_values": [ - "restricted_values_value1", - "restricted_values_value2", - ], - "prefixes": ["prefixes_value1", "prefixes_value2"], - "contains": ["contains_value1", "contains_value2"], - "case_insensitive": True, - "order_by": "order_by_value", - "query": "query_value", - "return_min_max": True, - }, - "limit": 543, - "excluded_filter_keys": [ - "excluded_filter_keys_value1", - "excluded_filter_keys_value2", - ], - "enable_dynamic_position": True, - }, - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "name_value", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = control_service.CreateControlRequest.meta.fields["control"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - - -def test_create_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -3672,100 +3264,21 @@ def test_create_control_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( +def test_create_control_rest_flattened(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), + transport="rest", ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_create_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.CreateControlRequest.pb( - control_service.CreateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.CreateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.create_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() + # 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 = gcr_control.Control() - -def test_create_control_rest_bad_request( - transport: str = "rest", request_type=control_service.CreateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_control(request) - - -def test_create_control_rest_flattened(): - client = ControlServiceClient( - 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 = gcr_control.Control() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -3826,49 +3339,6 @@ def test_create_control_rest_flattened_error(transport: str = "rest"): ) -def test_create_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.DeleteControlRequest, - dict, - ], -) -def test_delete_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_control(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3985,81 +3455,6 @@ def test_delete_control_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" - ) as pre: - pre.assert_not_called() - pb_message = control_service.DeleteControlRequest.pb( - control_service.DeleteControlRequest() - ) - 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() - - request = control_service.DeleteControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_control_rest_bad_request( - transport: str = "rest", request_type=control_service.DeleteControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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.delete_control(request) - - def test_delete_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4117,198 +3512,153 @@ def test_delete_control_rest_flattened_error(transport: str = "rest"): ) -def test_delete_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_control in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_control] = mock_rpc + + request = {} + client.update_control(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_control(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_control_rest_required_fields( + request_type=control_service.UpdateControlRequest, +): + transport_class = transports.ControlServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_control._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_control._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 -@pytest.mark.parametrize( - "request_type", - [ - control_service.UpdateControlRequest, - dict, - ], -) -def test_update_control_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - request_init["control"] = { - "facet_spec": { - "facet_key": { - "key": "key_value", - "intervals": [ - { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - } - ], - "restricted_values": [ - "restricted_values_value1", - "restricted_values_value2", - ], - "prefixes": ["prefixes_value1", "prefixes_value2"], - "contains": ["contains_value1", "contains_value2"], - "case_insensitive": True, - "order_by": "order_by_value", - "query": "query_value", - "return_min_max": True, - }, - "limit": 543, - "excluded_filter_keys": [ - "excluded_filter_keys_value1", - "excluded_filter_keys_value2", - ], - "enable_dynamic_position": True, - }, - "rule": { - "boost_action": { - "boost": 0.551, - "products_filter": "products_filter_value", - }, - "redirect_action": {"redirect_uri": "redirect_uri_value"}, - "oneway_synonyms_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "synonyms": ["synonyms_value1", "synonyms_value2"], - "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], - }, - "do_not_associate_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "do_not_associate_terms": [ - "do_not_associate_terms_value1", - "do_not_associate_terms_value2", - ], - "terms": ["terms_value1", "terms_value2"], - }, - "replacement_action": { - "query_terms": ["query_terms_value1", "query_terms_value2"], - "replacement_term": "replacement_term_value", - "term": "term_value", - }, - "ignore_action": { - "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] - }, - "filter_action": {"filter": "filter_value"}, - "twoway_synonyms_action": { - "synonyms": ["synonyms_value1", "synonyms_value2"] - }, - "force_return_facet_action": { - "facet_position_adjustments": [ - {"attribute_name": "attribute_name_value", "position": 885} - ] - }, - "remove_facet_action": { - "attribute_names": ["attribute_names_value1", "attribute_names_value2"] - }, - "condition": { - "query_terms": [{"value": "value_value", "full_match": True}], - "active_time_range": [ - {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} - ], - "page_categories": ["page_categories_value1", "page_categories_value2"], - }, - }, - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", - "display_name": "display_name_value", - "associated_serving_config_ids": [ - "associated_serving_config_ids_value1", - "associated_serving_config_ids_value2", - ], - "solution_types": [1], - "search_solution_use_case": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = gcr_control.Control() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = control_service.UpdateControlRequest.meta.fields["control"] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.update_control(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["control"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_control_rest_unset_required_fields(): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.update_control._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("control",))) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["control"][field])): - del request_init["control"][field][i][subfield] - else: - del request_init["control"][field][subfield] - request = request_type(**request_init) + +def test_update_control_rest_flattened(): + client = ControlServiceClient( + 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 = gcr_control.Control( - name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], + return_value = gcr_control.Control() + + # get arguments that satisfy an http rule for this method + sample_request = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + control=gcr_control.Control( + facet_spec=search_service.SearchRequest.FacetSpec( + facet_key=search_service.SearchRequest.FacetSpec.FacetKey( + key="key_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() @@ -4316,25 +3666,45 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gcr_control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_control(request) - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] + client.update_control(**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/v2beta/{control.name=projects/*/locations/*/catalogs/*/controls/*}" + % client.transport._host, + args[1], + ) -def test_update_control_rest_use_cached_wrapped_rpc(): +def test_update_control_rest_flattened_error(transport: str = "rest"): + client = ControlServiceClient( + 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_control( + control_service.UpdateControlRequest(), + control=gcr_control.Control( + facet_spec=search_service.SearchRequest.FacetSpec( + facet_key=search_service.SearchRequest.FacetSpec.FacetKey( + key="key_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4348,34 +3718,35 @@ def test_update_control_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_control in client._transport._wrapped_methods + assert client._transport.get_control in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_control] = mock_rpc + client._transport._wrapped_methods[client._transport.get_control] = mock_rpc request = {} - client.update_control(request) + client.get_control(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_control(request) + client.get_control(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_control_rest_required_fields( - request_type=control_service.UpdateControlRequest, +def test_get_control_rest_required_fields( + request_type=control_service.GetControlRequest, ): transport_class = transports.ControlServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4386,19 +3757,21 @@ def test_update_control_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_control._get_unset_required_fields(jsonified_request) + ).get_control._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() - ).update_control._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",)) + ).get_control._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 = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4407,7 +3780,7 @@ def test_update_control_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_control.Control() + return_value = control.Control() # 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 @@ -4419,122 +3792,38 @@ def test_update_control_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_control(request) + response = client.get_control(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_control_rest_unset_required_fields(): +def test_get_control_rest_unset_required_fields(): transport = transports.ControlServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_control._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("control",))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), - ) - client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_update_control" - ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_update_control" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = control_service.UpdateControlRequest.pb( - control_service.UpdateControlRequest() - ) - 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 = gcr_control.Control.to_json(gcr_control.Control()) - - request = control_service.UpdateControlRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_control.Control() - - client.update_control( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_control_rest_bad_request( - transport: str = "rest", request_type=control_service.UpdateControlRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - } - 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_control(request) + unset_fields = transport.get_control._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_update_control_rest_flattened(): +def test_get_control_rest_flattened(): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4543,25 +3832,16 @@ def test_update_control_rest_flattened(): # 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 = gcr_control.Control() + return_value = control.Control() # get arguments that satisfy an http rule for this method sample_request = { - "control": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" } # get truthy value for each flattened field mock_args = dict( - control=gcr_control.Control( - facet_spec=search_service.SearchRequest.FacetSpec( - facet_key=search_service.SearchRequest.FacetSpec.FacetKey( - key="key_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -4569,25 +3849,25 @@ def test_update_control_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_control.Control.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_control(**mock_args) + client.get_control(**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/v2beta/{control.name=projects/*/locations/*/catalogs/*/controls/*}" + "%s/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}" % client.transport._host, args[1], ) -def test_update_control_rest_flattened_error(transport: str = "rest"): +def test_get_control_rest_flattened_error(transport: str = "rest"): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4596,82 +3876,13 @@ def test_update_control_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_control( - control_service.UpdateControlRequest(), - control=gcr_control.Control( - facet_spec=search_service.SearchRequest.FacetSpec( - facet_key=search_service.SearchRequest.FacetSpec.FacetKey( - key="key_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - control_service.GetControlRequest, - dict, - ], -) -def test_get_control_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - 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 = control.Control( + client.get_control( + control_service.GetControlRequest(), name="name_value", - display_name="display_name_value", - associated_serving_config_ids=["associated_serving_config_ids_value"], - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - search_solution_use_case=[ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ], ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_control(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, control.Control) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.associated_serving_config_ids == [ - "associated_serving_config_ids_value" - ] - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.search_solution_use_case == [ - common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH - ] - -def test_get_control_rest_use_cached_wrapped_rpc(): +def test_list_controls_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4685,35 +3896,35 @@ def test_get_control_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_control in client._transport._wrapped_methods + assert client._transport.list_controls in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_control] = mock_rpc + client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc request = {} - client.get_control(request) + client.list_controls(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_control(request) + client.list_controls(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_control_rest_required_fields( - request_type=control_service.GetControlRequest, +def test_list_controls_rest_required_fields( + request_type=control_service.ListControlsRequest, ): transport_class = transports.ControlServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4724,21 +3935,29 @@ def test_get_control_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_control._get_unset_required_fields(jsonified_request) + ).list_controls._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_control._get_unset_required_fields(jsonified_request) + ).list_controls._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4747,7 +3966,7 @@ def test_get_control_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = control.Control() + return_value = control_service.ListControlsResponse() # 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 @@ -4768,50 +3987,1199 @@ def test_get_control_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = control.Control.pb(return_value) + return_value = control_service.ListControlsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_control(request) + response = client.list_controls(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_control_rest_unset_required_fields(): +def test_list_controls_rest_unset_required_fields(): transport = transports.ControlServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_control._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_controls._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_control_rest_interceptors(null_interceptor): - transport = transports.ControlServiceRestTransport( +def test_list_controls_rest_flattened(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ControlServiceRestInterceptor(), + transport="rest", ) - client = ControlServiceClient(transport=transport) - with mock.patch.object( + + # 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 = control_service.ListControlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = control_service.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_controls(**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/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls" + % client.transport._host, + args[1], + ) + + +def test_list_controls_rest_flattened_error(transport: str = "rest"): + client = ControlServiceClient( + 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.list_controls( + control_service.ListControlsRequest(), + parent="parent_value", + ) + + +def test_list_controls_rest_pager(transport: str = "rest"): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + control.Control(), + ], + next_page_token="abc", + ), + control_service.ListControlsResponse( + controls=[], + next_page_token="def", + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + ], + next_page_token="ghi", + ), + control_service.ListControlsResponse( + controls=[ + control.Control(), + control.Control(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + control_service.ListControlsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } + + pager = client.list_controls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, control.Control) for i in results) + + pages = list(client.list_controls(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ControlServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ControlServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ControlServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ControlServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ControlServiceGrpcTransport, + transports.ControlServiceGrpcAsyncIOTransport, + transports.ControlServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ControlServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + call.return_value = None + client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + call.return_value = gcr_control.Control() + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + call.return_value = control.Control() + client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + call.return_value = control_service.ListControlsResponse() + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ControlServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.create_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_control_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + ) + await client.get_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_controls_empty_call_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ControlServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_control_rest_bad_request( + request_type=control_service.CreateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.CreateControlRequest, + dict, + ], +) +def test_create_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["control"] = { + "facet_spec": { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + "query": "query_value", + "return_min_max": True, + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + }, + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "name_value", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.CreateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_create_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_create_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.CreateControlRequest.pb( + control_service.CreateControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value + + request = control_service.CreateControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_control.Control() + + client.create_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_control_rest_bad_request( + request_type=control_service.DeleteControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.DeleteControlRequest, + dict, + ], +) +def test_delete_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_control(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "pre_delete_control" + ) as pre: + pre.assert_not_called() + pb_message = control_service.DeleteControlRequest.pb( + control_service.DeleteControlRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = control_service.DeleteControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_control_rest_bad_request( + request_type=control_service.UpdateControlRequest, +): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_control(request) + + +@pytest.mark.parametrize( + "request_type", + [ + control_service.UpdateControlRequest, + dict, + ], +) +def test_update_control_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "control": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } + } + request_init["control"] = { + "facet_spec": { + "facet_key": { + "key": "key_value", + "intervals": [ + { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + } + ], + "restricted_values": [ + "restricted_values_value1", + "restricted_values_value2", + ], + "prefixes": ["prefixes_value1", "prefixes_value2"], + "contains": ["contains_value1", "contains_value2"], + "case_insensitive": True, + "order_by": "order_by_value", + "query": "query_value", + "return_min_max": True, + }, + "limit": 543, + "excluded_filter_keys": [ + "excluded_filter_keys_value1", + "excluded_filter_keys_value2", + ], + "enable_dynamic_position": True, + }, + "rule": { + "boost_action": { + "boost": 0.551, + "products_filter": "products_filter_value", + }, + "redirect_action": {"redirect_uri": "redirect_uri_value"}, + "oneway_synonyms_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "synonyms": ["synonyms_value1", "synonyms_value2"], + "oneway_terms": ["oneway_terms_value1", "oneway_terms_value2"], + }, + "do_not_associate_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "do_not_associate_terms": [ + "do_not_associate_terms_value1", + "do_not_associate_terms_value2", + ], + "terms": ["terms_value1", "terms_value2"], + }, + "replacement_action": { + "query_terms": ["query_terms_value1", "query_terms_value2"], + "replacement_term": "replacement_term_value", + "term": "term_value", + }, + "ignore_action": { + "ignore_terms": ["ignore_terms_value1", "ignore_terms_value2"] + }, + "filter_action": {"filter": "filter_value"}, + "twoway_synonyms_action": { + "synonyms": ["synonyms_value1", "synonyms_value2"] + }, + "force_return_facet_action": { + "facet_position_adjustments": [ + {"attribute_name": "attribute_name_value", "position": 885} + ] + }, + "remove_facet_action": { + "attribute_names": ["attribute_names_value1", "attribute_names_value2"] + }, + "condition": { + "query_terms": [{"value": "value_value", "full_match": True}], + "active_time_range": [ + {"start_time": {"seconds": 751, "nanos": 543}, "end_time": {}} + ], + "page_categories": ["page_categories_value1", "page_categories_value2"], + }, + }, + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4", + "display_name": "display_name_value", + "associated_serving_config_ids": [ + "associated_serving_config_ids_value1", + "associated_serving_config_ids_value2", + ], + "solution_types": [1], + "search_solution_use_case": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = control_service.UpdateControlRequest.meta.fields["control"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["control"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["control"][field])): + del request_init["control"][field][i][subfield] + else: + del request_init["control"][field][subfield] + 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 = gcr_control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_control.Control.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_control(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(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.ControlServiceRestInterceptor, "post_get_control" + transports.ControlServiceRestInterceptor, "post_update_control" ) as post, mock.patch.object( - transports.ControlServiceRestInterceptor, "pre_get_control" + transports.ControlServiceRestInterceptor, "pre_update_control" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = control_service.GetControlRequest.pb( - control_service.GetControlRequest() + pb_message = control_service.UpdateControlRequest.pb( + control_service.UpdateControlRequest() ) transcode.return_value = { "method": "post", @@ -4820,20 +5188,20 @@ def test_get_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = control.Control.to_json(control.Control()) + return_value = gcr_control.Control.to_json(gcr_control.Control()) + req.return_value.content = return_value - request = control_service.GetControlRequest() + request = control_service.UpdateControlRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = control.Control() + post.return_value = gcr_control.Control() - client.get_control( + client.update_control( request, metadata=[ ("key", "val"), @@ -4845,14 +5213,10 @@ def test_get_control_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_control_rest_bad_request( - transport: str = "rest", request_type=control_service.GetControlRequest -): +def test_get_control_rest_bad_request(request_type=control_service.GetControlRequest): client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" @@ -4864,252 +5228,187 @@ def test_get_control_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.get_control(request) -def test_get_control_rest_flattened(): - client = ControlServiceClient( - 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 = control.Control() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" - } - - # 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 - # Convert return value to protobuf type - return_value = control.Control.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_control(**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/v2beta/{name=projects/*/locations/*/catalogs/*/controls/*}" - % client.transport._host, - args[1], - ) - - -def test_get_control_rest_flattened_error(transport: str = "rest"): - client = ControlServiceClient( - 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_control( - control_service.GetControlRequest(), - name="name_value", - ) - - -def test_get_control_rest_error(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - control_service.ListControlsRequest, + control_service.GetControlRequest, dict, ], ) -def test_list_controls_rest(request_type): +def test_get_control_rest_call_success(request_type): client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/controls/sample4" + } 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 = control_service.ListControlsResponse( - next_page_token="next_page_token_value", + return_value = control.Control( + name="name_value", + display_name="display_name_value", + associated_serving_config_ids=["associated_serving_config_ids_value"], + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + search_solution_use_case=[ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) + return_value = control.Control.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_controls(request) + response = client.get_control(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListControlsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_controls_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + assert isinstance(response, control.Control) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.associated_serving_config_ids == [ + "associated_serving_config_ids_value" + ] + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.search_solution_use_case == [ + common.SearchSolutionUseCase.SEARCH_SOLUTION_USE_CASE_SEARCH + ] - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.list_controls in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_control_rest_interceptors(null_interceptor): + transport = transports.ControlServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ControlServiceRestInterceptor(), + ) + client = ControlServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ControlServiceRestInterceptor, "post_get_control" + ) as post, mock.patch.object( + transports.ControlServiceRestInterceptor, "pre_get_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = control_service.GetControlRequest.pb( + control_service.GetControlRequest() ) - client._transport._wrapped_methods[client._transport.list_controls] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.list_controls(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = control.Control.to_json(control.Control()) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = control_service.GetControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = control.Control() - client.list_controls(request) + client.get_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_list_controls_rest_required_fields( +def test_list_controls_rest_bad_request( request_type=control_service.ListControlsRequest, ): - transport_class = transports.ControlServiceRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_controls._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() - ).list_controls._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - ) - ) - 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 = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = control_service.ListControlsResponse() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_controls(request) - # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + control_service.ListControlsRequest, + dict, + ], +) +def test_list_controls_rest_call_success(request_type): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.list_controls(request) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = control_service.ListControlsResponse( + next_page_token="next_page_token_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_list_controls_rest_unset_required_fields(): - transport = transports.ControlServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = control_service.ListControlsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_controls(request) - unset_fields = transport.list_controls._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListControlsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5121,6 +5420,7 @@ def test_list_controls_rest_interceptors(null_interceptor): else transports.ControlServiceRestInterceptor(), ) client = ControlServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5142,12 +5442,12 @@ def test_list_controls_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = control_service.ListControlsResponse.to_json( + return_value = control_service.ListControlsResponse.to_json( control_service.ListControlsResponse() ) + req.return_value.content = return_value request = control_service.ListControlsRequest() metadata = [ @@ -5169,17 +5469,20 @@ def test_list_controls_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_controls_rest_bad_request( - transport: str = "rest", request_type=control_service.ListControlsRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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( @@ -5187,240 +5490,215 @@ def test_list_controls_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_controls(request) + client.get_operation(request) -def test_list_controls_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + 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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = control_service.ListControlsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = control_service.ListControlsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.list_controls(**mock_args) + response = client.get_operation(request) - # 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/v2beta/{parent=projects/*/locations/*/catalogs/*}/controls" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_list_controls_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_controls( - control_service.ListControlsRequest(), - parent="parent_value", - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -def test_list_controls_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - control.Control(), - ], - next_page_token="abc", - ), - control_service.ListControlsResponse( - controls=[], - next_page_token="def", - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - ], - next_page_token="ghi", - ), - control_service.ListControlsResponse( - controls=[ - control.Control(), - control.Control(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - control_service.ListControlsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - pager = client.list_controls(request=sample_request) + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, control.Control) for i in results) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - pages = list(client.list_controls(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + req.return_value = response_value + response = client.list_operations(request) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ControlServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, - transport=transport, - ) +def test_initialize_client_w_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.ControlServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ControlServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_control), "__call__") as call: + client.create_control(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.CreateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ControlServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_control), "__call__") as call: + client.delete_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.DeleteControlRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ControlServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ControlServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_control), "__call__") as call: + client.update_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.UpdateControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_control_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_control), "__call__") as call: + client.get_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ControlServiceGrpcTransport, - transports.ControlServiceGrpcAsyncIOTransport, - transports.ControlServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.GetControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ControlServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_controls_empty_call_rest(): + client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_controls), "__call__") as call: + client.list_controls(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = control_service.ListControlsRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -6045,141 +6323,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ControlServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6207,7 +6350,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6262,7 +6405,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6309,7 +6452,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6352,7 +6495,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6407,7 +6550,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6454,7 +6597,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ControlServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6470,22 +6613,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ControlServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ControlServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ControlServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_generative_question_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_generative_question_service.py index 7ff0edd787e2..0ece78d3e3a9 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_generative_question_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_generative_question_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2beta.services.generative_question_service import ( GenerativeQuestionServiceAsyncClient, @@ -57,10 +66,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1252,30 +1275,6 @@ def test_update_generative_questions_feature_config( assert response.minimum_products == 1743 -def test_update_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - def test_update_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1347,36 +1346,6 @@ def test_update_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.update_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1385,7 +1354,7 @@ async def test_update_generative_questions_feature_config_async_use_cached_wrapp # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1425,7 +1394,7 @@ async def test_update_generative_questions_feature_config_async( request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1503,7 +1472,7 @@ def test_update_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1590,7 +1559,7 @@ def test_update_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1629,7 +1598,7 @@ async def test_update_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1688,30 +1657,6 @@ def test_get_generative_questions_feature_config(request_type, transport: str = assert response.minimum_products == 1743 -def test_get_generative_questions_feature_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - def test_get_generative_questions_feature_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1784,36 +1729,6 @@ def test_get_generative_questions_feature_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_generative_questions_feature_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_generative_questions_feature_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - ) - response = await client.get_generative_questions_feature_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - - @pytest.mark.asyncio async def test_get_generative_questions_feature_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1822,7 +1737,7 @@ async def test_get_generative_questions_feature_config_async_use_cached_wrapped_ # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1862,7 +1777,7 @@ async def test_get_generative_questions_feature_config_async( request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1938,7 +1853,7 @@ def test_get_generative_questions_feature_config_field_headers(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2012,7 +1927,7 @@ def test_get_generative_questions_feature_config_flattened_error(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2043,7 +1958,7 @@ async def test_get_generative_questions_feature_config_flattened_async(): @pytest.mark.asyncio async def test_get_generative_questions_feature_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,30 +2009,6 @@ def test_list_generative_question_configs(request_type, transport: str = "grpc") ) -def test_list_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - def test_list_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2190,32 +2081,6 @@ def test_list_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - response = await client.list_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.ListGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2224,7 +2089,7 @@ async def test_list_generative_question_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2264,7 +2129,7 @@ async def test_list_generative_question_configs_async( request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2335,7 +2200,7 @@ def test_list_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_list_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2411,7 +2276,7 @@ def test_list_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2444,7 +2309,7 @@ async def test_list_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_list_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2506,30 +2371,6 @@ def test_update_generative_question_config(request_type, transport: str = "grpc" assert response.allowed_in_conversation is True -def test_update_generative_question_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - def test_update_generative_question_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2599,40 +2440,6 @@ def test_update_generative_question_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_generative_question_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_generative_question_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - ) - response = await client.update_generative_question_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - - @pytest.mark.asyncio async def test_update_generative_question_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2641,7 +2448,7 @@ async def test_update_generative_question_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2681,7 +2488,7 @@ async def test_update_generative_question_config_async( request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2763,7 +2570,7 @@ def test_update_generative_question_config_field_headers(): @pytest.mark.asyncio async def test_update_generative_question_config_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2846,7 +2653,7 @@ def test_update_generative_question_config_flattened_error(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2883,7 +2690,7 @@ async def test_update_generative_question_config_flattened_async(): @pytest.mark.asyncio async def test_update_generative_question_config_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2942,30 +2749,6 @@ def test_batch_update_generative_question_configs( ) -def test_batch_update_generative_question_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - def test_batch_update_generative_question_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3038,32 +2821,6 @@ def test_batch_update_generative_question_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_batch_update_generative_question_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_generative_question_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - response = await client.batch_update_generative_question_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert ( - args[0] - == generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - - @pytest.mark.asyncio async def test_batch_update_generative_question_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3072,7 +2829,7 @@ async def test_batch_update_generative_question_configs_async_use_cached_wrapped # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3112,7 +2869,7 @@ async def test_batch_update_generative_question_configs_async( request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, ): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3186,7 +2943,7 @@ def test_batch_update_generative_question_configs_field_headers(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3285,7 +3042,7 @@ def test_batch_update_generative_question_configs_flattened_error(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3334,7 +3091,7 @@ async def test_batch_update_generative_question_configs_flattened_async(): @pytest.mark.asyncio async def test_batch_update_generative_question_configs_flattened_error_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3353,136 +3110,6 @@ async def test_batch_update_generative_question_configs_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_update_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_questions_feature_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "feature_enabled": True, - "minimum_products": 1743, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ - "generative_questions_feature_config" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_questions_feature_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_questions_feature_config"][field]) - ): - del request_init["generative_questions_feature_config"][field][i][ - subfield - ] - else: - del request_init["generative_questions_feature_config"][field][subfield] - 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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - def test_update_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3617,98 +3244,6 @@ def test_update_generative_questions_feature_config_rest_unset_required_fields() ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.update_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_questions_feature_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_questions_feature_config(request) - - def test_update_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3780,70 +3315,18 @@ def test_update_generative_questions_feature_config_rest_flattened_error( ) -def test_update_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, - dict, - ], -) -def test_get_generative_questions_feature_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( - catalog="catalog_value", - feature_enabled=True, - minimum_products=1743, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_generative_questions_feature_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) - assert response.catalog == "catalog_value" - assert response.feature_enabled is True - assert response.minimum_products == 1743 - - -def test_get_generative_questions_feature_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert ( @@ -3964,96 +3447,6 @@ def test_get_generative_questions_feature_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("catalog",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_get_generative_questions_feature_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_get_generative_questions_feature_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionsFeatureConfig.to_json( - generative_question.GenerativeQuestionsFeatureConfig() - ) - ) - - request = ( - generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionsFeatureConfig() - - client.get_generative_questions_feature_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_generative_questions_feature_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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.get_generative_questions_feature_config(request) - - def test_get_generative_questions_feature_config_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4117,57 +3510,6 @@ def test_get_generative_questions_feature_config_rest_flattened_error( ) -def test_get_generative_questions_feature_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.ListGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_list_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, generative_question_service.ListGenerativeQuestionConfigsResponse - ) - - def test_list_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4298,132 +3640,42 @@ def test_list_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_list_generative_question_configs_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_list_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_list_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.ListGenerativeQuestionConfigsRequest.pb( - generative_question_service.ListGenerativeQuestionConfigsRequest() - ) + + # 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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) - request = generative_question_service.ListGenerativeQuestionConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) ) - - client.list_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_generative_question_configs(request) - - -def test_list_generative_question_configs_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = ( - generative_question_service.ListGenerativeQuestionConfigsResponse() - ) - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.ListGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value client.list_generative_question_configs(**mock_args) @@ -4453,152 +3705,6 @@ def test_list_generative_question_configs_rest_flattened_error(transport: str = ) -def test_list_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.UpdateGenerativeQuestionConfigRequest, - dict, - ], -) -def test_update_generative_question_config_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3" - } - } - request_init["generative_question_config"] = { - "catalog": "projects/sample1/locations/sample2/catalogs/sample3", - "facet": "facet_value", - "generated_question": "generated_question_value", - "final_question": "final_question_value", - "example_values": ["example_values_value1", "example_values_value2"], - "frequency": 0.978, - "allowed_in_conversation": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ - "generative_question_config" - ] - ) - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "generative_question_config" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["generative_question_config"][field]) - ): - del request_init["generative_question_config"][field][i][subfield] - else: - del request_init["generative_question_config"][field][subfield] - 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 = generative_question.GenerativeQuestionConfig( - catalog="catalog_value", - facet="facet_value", - generated_question="generated_question_value", - final_question="final_question_value", - example_values=["example_values_value"], - frequency=0.978, - allowed_in_conversation=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = generative_question.GenerativeQuestionConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_generative_question_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, generative_question.GenerativeQuestionConfig) - assert response.catalog == "catalog_value" - assert response.facet == "facet_value" - assert response.generated_question == "generated_question_value" - assert response.final_question == "final_question_value" - assert response.example_values == ["example_values_value"] - assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) - assert response.allowed_in_conversation is True - - def test_update_generative_question_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4725,108 +3831,16 @@ def test_update_generative_question_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_generative_question_config_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( +def test_update_generative_question_config_rest_flattened(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), + transport="rest", ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_update_generative_question_config", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_update_generative_question_config", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ( - generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( - generative_question_service.UpdateGenerativeQuestionConfigRequest() - ) - ) - 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 = ( - generative_question.GenerativeQuestionConfig.to_json( - generative_question.GenerativeQuestionConfig() - ) - ) - - request = generative_question_service.UpdateGenerativeQuestionConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = generative_question.GenerativeQuestionConfig() - - client.update_generative_question_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_generative_question_config_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "generative_question_config": { - "catalog": "projects/sample1/locations/sample2/catalogs/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.update_generative_question_config(request) - - -def test_update_generative_question_config_rest_flattened(): - client = GenerativeQuestionServiceClient( - 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 = generative_question.GenerativeQuestionConfig() + # 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 = generative_question.GenerativeQuestionConfig() # get arguments that satisfy an http rule for this method sample_request = { @@ -4886,58 +3900,6 @@ def test_update_generative_question_config_rest_flattened_error( ) -def test_update_generative_question_config_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, - dict, - ], -) -def test_batch_update_generative_question_configs_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.batch_update_generative_question_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance( - response, - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, - ) - - def test_batch_update_generative_question_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5070,94 +4032,6 @@ def test_batch_update_generative_question_configs_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("requests",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): - transport = transports.GenerativeQuestionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.GenerativeQuestionServiceRestInterceptor(), - ) - client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, - "post_batch_update_generative_question_configs", - ) as post, mock.patch.object( - transports.GenerativeQuestionServiceRestInterceptor, - "pre_batch_update_generative_question_configs", - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - 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 = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - request = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() - ) - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ( - generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() - ) - - client.batch_update_generative_question_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_update_generative_question_configs_rest_bad_request( - transport: str = "rest", - request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.batch_update_generative_question_configs(request) - - def test_batch_update_generative_question_configs_rest_flattened(): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5239,12 +4113,6 @@ def test_batch_update_generative_question_configs_rest_flattened_error( ) -def test_batch_update_generative_question_configs_rest_error(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GenerativeQuestionServiceGrpcTransport( @@ -5286,69 +4154,1474 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GenerativeQuestionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GenerativeQuestionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GenerativeQuestionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GenerativeQuestionServiceGrpcTransport, + transports.GenerativeQuestionServiceGrpcAsyncIOTransport, + transports.GenerativeQuestionServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = GenerativeQuestionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionsFeatureConfig() + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + call.return_value = generative_question.GenerativeQuestionConfig() + client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + call.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GenerativeQuestionServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_generative_questions_feature_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + ) + await client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + await client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_generative_question_config_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + ) + await client.update_generative_question_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_generative_question_configs_empty_call_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + await client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GenerativeQuestionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_update_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_update_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_questions_feature_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_questions_feature_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "feature_enabled": True, + "minimum_products": 1743, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.meta.fields[ + "generative_questions_feature_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_questions_feature_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_questions_feature_config"][field]) + ): + del request_init["generative_questions_feature_config"][field][i][ + subfield + ] + else: + del request_init["generative_questions_feature_config"][field][subfield] + 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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.update_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_generative_questions_feature_config_rest_bad_request( + request_type=generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_generative_questions_feature_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest, + dict, + ], +) +def test_get_generative_questions_feature_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"catalog": "projects/sample1/locations/sample2/catalogs/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 = generative_question.GenerativeQuestionsFeatureConfig( + catalog="catalog_value", + feature_enabled=True, + minimum_products=1743, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionsFeatureConfig.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_generative_questions_feature_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionsFeatureConfig) + assert response.catalog == "catalog_value" + assert response.feature_enabled is True + assert response.minimum_products == 1743 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_generative_questions_feature_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_get_generative_questions_feature_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_get_generative_questions_feature_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest.pb( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionsFeatureConfig.to_json( + generative_question.GenerativeQuestionsFeatureConfig() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionsFeatureConfig() + + client.get_generative_questions_feature_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_generative_question_configs_rest_bad_request( + request_type=generative_question_service.ListGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.ListGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_list_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, generative_question_service.ListGenerativeQuestionConfigsResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_list_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_list_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.ListGenerativeQuestionConfigsRequest.pb( + generative_question_service.ListGenerativeQuestionConfigsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse.to_json( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + ) + req.return_value.content = return_value + + request = generative_question_service.ListGenerativeQuestionConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.ListGenerativeQuestionConfigsResponse() + ) + + client.list_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_generative_question_config_rest_bad_request( + request_type=generative_question_service.UpdateGenerativeQuestionConfigRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_generative_question_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.UpdateGenerativeQuestionConfigRequest, + dict, + ], +) +def test_update_generative_question_config_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "generative_question_config": { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3" + } + } + request_init["generative_question_config"] = { + "catalog": "projects/sample1/locations/sample2/catalogs/sample3", + "facet": "facet_value", + "generated_question": "generated_question_value", + "final_question": "final_question_value", + "example_values": ["example_values_value1", "example_values_value2"], + "frequency": 0.978, + "allowed_in_conversation": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.meta.fields[ + "generative_question_config" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "generative_question_config" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["generative_question_config"][field]) + ): + del request_init["generative_question_config"][field][i][subfield] + else: + del request_init["generative_question_config"][field][subfield] + 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 = generative_question.GenerativeQuestionConfig( + catalog="catalog_value", + facet="facet_value", + generated_question="generated_question_value", + final_question="final_question_value", + example_values=["example_values_value"], + frequency=0.978, + allowed_in_conversation=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = generative_question.GenerativeQuestionConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_generative_question_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generative_question.GenerativeQuestionConfig) + assert response.catalog == "catalog_value" + assert response.facet == "facet_value" + assert response.generated_question == "generated_question_value" + assert response.final_question == "final_question_value" + assert response.example_values == ["example_values_value"] + assert math.isclose(response.frequency, 0.978, rel_tol=1e-6) + assert response.allowed_in_conversation is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_generative_question_config_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_update_generative_question_config", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_update_generative_question_config", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest.pb( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question.GenerativeQuestionConfig.to_json( + generative_question.GenerativeQuestionConfig() + ) + req.return_value.content = return_value + + request = generative_question_service.UpdateGenerativeQuestionConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generative_question.GenerativeQuestionConfig() + + client.update_generative_question_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_update_generative_question_configs_rest_bad_request( + request_type=generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.batch_update_generative_question_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest, + dict, + ], +) +def test_batch_update_generative_question_configs_rest_call_success(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.batch_update_generative_question_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse, + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_generative_question_configs_rest_interceptors(null_interceptor): + transport = transports.GenerativeQuestionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GenerativeQuestionServiceRestInterceptor(), + ) + client = GenerativeQuestionServiceClient(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.GenerativeQuestionServiceRestInterceptor, + "post_batch_update_generative_question_configs", + ) as post, mock.patch.object( + transports.GenerativeQuestionServiceRestInterceptor, + "pre_batch_update_generative_question_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest.pb( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse.to_json( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + req.return_value.content = return_value + + request = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsResponse() + ) + + client.batch_update_generative_question_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_questions_feature_config), "__call__" + ) as call: + client.update_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionsFeatureConfigRequest() + ) + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_generative_questions_feature_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = GenerativeQuestionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generative_questions_feature_config), "__call__" + ) as call: + client.get_generative_questions_feature_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.GetGenerativeQuestionsFeatureConfigRequest() ) + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = GenerativeQuestionServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generative_question_configs), "__call__" + ) as call: + client.list_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generative_question_service.ListGenerativeQuestionConfigsRequest() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GenerativeQuestionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + assert args[0] == request_msg - transport = transports.GenerativeQuestionServiceGrpcAsyncIOTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_generative_question_config_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_generative_question_config), "__call__" + ) as call: + client.update_generative_question_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.GenerativeQuestionServiceGrpcTransport, - transports.GenerativeQuestionServiceGrpcAsyncIOTransport, - transports.GenerativeQuestionServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.UpdateGenerativeQuestionConfigRequest() + ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = GenerativeQuestionServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_generative_question_configs_empty_call_rest(): + client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_generative_question_configs), "__call__" + ) as call: + client.batch_update_generative_question_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + generative_question_service.BatchUpdateGenerativeQuestionConfigsRequest() + ) + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -5950,141 +6223,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = GenerativeQuestionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6112,7 +6250,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6167,7 +6305,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6214,7 +6352,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -6257,7 +6395,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6312,7 +6450,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6359,7 +6497,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = GenerativeQuestionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6375,22 +6513,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = GenerativeQuestionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = GenerativeQuestionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = GenerativeQuestionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_model_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_model_service.py index 1e4d62457096..f51615d9b39d 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_model_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_model_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.retail_v2beta.services.model_service import ( ModelServiceAsyncClient, @@ -68,10 +77,24 @@ from google.cloud.retail_v2beta.types import model_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1143,25 +1166,6 @@ def test_create_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - def test_create_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1230,27 +1234,6 @@ def test_create_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.CreateModelRequest() - - @pytest.mark.asyncio async def test_create_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1259,7 +1242,7 @@ async def test_create_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1303,7 +1286,7 @@ async def test_create_model_async( transport: str = "grpc_asyncio", request_type=model_service.CreateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1366,7 +1349,7 @@ def test_create_model_field_headers(): @pytest.mark.asyncio async def test_create_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1441,7 +1424,7 @@ def test_create_model_flattened_error(): @pytest.mark.asyncio async def test_create_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1474,7 +1457,7 @@ async def test_create_model_flattened_async(): @pytest.mark.asyncio async def test_create_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1547,25 +1530,6 @@ def test_get_model(request_type, transport: str = "grpc"): ) -def test_get_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - def test_get_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1629,45 +1593,13 @@ def test_get_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.get_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.GetModelRequest() - - @pytest.mark.asyncio async def test_get_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1706,7 +1638,7 @@ async def test_get_model_async( transport: str = "grpc_asyncio", request_type=model_service.GetModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1796,7 +1728,7 @@ def test_get_model_field_headers(): @pytest.mark.asyncio async def test_get_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1864,7 +1796,7 @@ def test_get_model_flattened_error(): @pytest.mark.asyncio async def test_get_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1891,7 +1823,7 @@ async def test_get_model_flattened_async(): @pytest.mark.asyncio async def test_get_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1963,25 +1895,6 @@ def test_pause_model(request_type, transport: str = "grpc"): ) -def test_pause_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - def test_pause_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2045,38 +1958,6 @@ def test_pause_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_pause_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.pause_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.pause_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.PauseModelRequest() - - @pytest.mark.asyncio async def test_pause_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2085,7 +1966,7 @@ async def test_pause_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2124,7 +2005,7 @@ async def test_pause_model_async( transport: str = "grpc_asyncio", request_type=model_service.PauseModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2214,7 +2095,7 @@ def test_pause_model_field_headers(): @pytest.mark.asyncio async def test_pause_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2282,7 +2163,7 @@ def test_pause_model_flattened_error(): @pytest.mark.asyncio async def test_pause_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2309,7 +2190,7 @@ async def test_pause_model_flattened_async(): @pytest.mark.asyncio async def test_pause_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2381,25 +2262,6 @@ def test_resume_model(request_type, transport: str = "grpc"): ) -def test_resume_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - def test_resume_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2463,38 +2325,6 @@ def test_resume_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_resume_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.resume_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.resume_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ResumeModelRequest() - - @pytest.mark.asyncio async def test_resume_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2503,7 +2333,7 @@ async def test_resume_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2542,7 +2372,7 @@ async def test_resume_model_async( transport: str = "grpc_asyncio", request_type=model_service.ResumeModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2632,7 +2462,7 @@ def test_resume_model_field_headers(): @pytest.mark.asyncio async def test_resume_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2700,7 +2530,7 @@ def test_resume_model_flattened_error(): @pytest.mark.asyncio async def test_resume_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2727,7 +2557,7 @@ async def test_resume_model_flattened_async(): @pytest.mark.asyncio async def test_resume_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2772,25 +2602,6 @@ def test_delete_model(request_type, transport: str = "grpc"): assert response is None -def test_delete_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - def test_delete_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2854,25 +2665,6 @@ def test_delete_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.DeleteModelRequest() - - @pytest.mark.asyncio async def test_delete_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2881,7 +2673,7 @@ async def test_delete_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2920,7 +2712,7 @@ async def test_delete_model_async( transport: str = "grpc_asyncio", request_type=model_service.DeleteModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2981,7 +2773,7 @@ def test_delete_model_field_headers(): @pytest.mark.asyncio async def test_delete_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3049,7 +2841,7 @@ def test_delete_model_flattened_error(): @pytest.mark.asyncio async def test_delete_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3076,7 +2868,7 @@ async def test_delete_model_flattened_async(): @pytest.mark.asyncio async def test_delete_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3124,25 +2916,6 @@ def test_list_models(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_models_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - def test_list_models_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3208,29 +2981,6 @@ def test_list_models_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_models_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_models), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_models() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.ListModelsRequest() - - @pytest.mark.asyncio async def test_list_models_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3239,7 +2989,7 @@ async def test_list_models_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3278,7 +3028,7 @@ async def test_list_models_async( transport: str = "grpc_asyncio", request_type=model_service.ListModelsRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3344,7 +3094,7 @@ def test_list_models_field_headers(): @pytest.mark.asyncio async def test_list_models_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3414,7 +3164,7 @@ def test_list_models_flattened_error(): @pytest.mark.asyncio async def test_list_models_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3443,7 +3193,7 @@ async def test_list_models_flattened_async(): @pytest.mark.asyncio async def test_list_models_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3553,7 +3303,7 @@ def test_list_models_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_models_async_pager(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3603,7 +3353,7 @@ async def test_list_models_async_pager(): @pytest.mark.asyncio async def test_list_models_async_pages(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3709,25 +3459,6 @@ def test_update_model(request_type, transport: str = "grpc"): ) -def test_update_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - def test_update_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3787,38 +3518,6 @@ def test_update_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - ) - response = await client.update_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.UpdateModelRequest() - - @pytest.mark.asyncio async def test_update_model_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3827,7 +3526,7 @@ async def test_update_model_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3866,7 +3565,7 @@ async def test_update_model_async( transport: str = "grpc_asyncio", request_type=model_service.UpdateModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3956,7 +3655,7 @@ def test_update_model_field_headers(): @pytest.mark.asyncio async def test_update_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4029,7 +3728,7 @@ def test_update_model_flattened_error(): @pytest.mark.asyncio async def test_update_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4060,7 +3759,7 @@ async def test_update_model_flattened_async(): @pytest.mark.asyncio async def test_update_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4106,25 +3805,6 @@ def test_tune_model(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_tune_model_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - def test_tune_model_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4193,34 +3873,13 @@ def test_tune_model_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_tune_model_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.tune_model), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.tune_model() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == model_service.TuneModelRequest() - - @pytest.mark.asyncio async def test_tune_model_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4264,7 +3923,7 @@ async def test_tune_model_async( transport: str = "grpc_asyncio", request_type=model_service.TuneModelRequest ): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4327,7 +3986,7 @@ def test_tune_model_field_headers(): @pytest.mark.asyncio async def test_tune_model_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4397,7 +4056,7 @@ def test_tune_model_flattened_error(): @pytest.mark.asyncio async def test_tune_model_flattened_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4426,7 +4085,7 @@ async def test_tune_model_flattened_async(): @pytest.mark.asyncio async def test_tune_model_flattened_error_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4438,134 +4097,6 @@ async def test_tune_model_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - model_service.CreateModelRequest, - dict, - ], -) -def test_create_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["model"] = { - "name": "name_value", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1} - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.CreateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4697,93 +4228,10 @@ def test_create_model_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_create_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_create_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_create_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.CreateModelRequest.pb( - model_service.CreateModelRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.CreateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_model_rest_bad_request( - transport: str = "rest", request_type=model_service.CreateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_model(request) - - -def test_create_model_rest_flattened(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -4839,78 +4287,6 @@ def test_create_model_rest_flattened_error(transport: str = "rest"): ) -def test_create_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.GetModelRequest, - dict, - ], -) -def test_get_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_get_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5028,85 +4404,6 @@ def test_get_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_get_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) - 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 = model.Model.to_json(model.Model()) - - request = model_service.GetModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.get_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_model_rest_bad_request( - transport: str = "rest", request_type=model_service.GetModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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_model(request) - - def test_get_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5166,103 +4463,31 @@ def test_get_model_rest_flattened_error(transport: str = "rest"): ) -def test_get_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - +def test_pause_model_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -@pytest.mark.parametrize( - "request_type", - [ - model_service.PauseModelRequest, - dict, - ], -) -def test_pause_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - request = request_type(**request_init) + # Ensure method has been cached + assert client._transport.pause_model in client._transport._wrapped_methods - # 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.pause_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - -def test_pause_model_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.pause_model in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.pause_model] = mock_rpc - - request = {} - client.pause_model(request) + request = {} + client.pause_model(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5356,87 +4581,6 @@ def test_pause_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_pause_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_pause_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.PauseModelRequest.pb( - model_service.PauseModelRequest() - ) - 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 = model.Model.to_json(model.Model()) - - request = model_service.PauseModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() - - client.pause_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_pause_model_rest_bad_request( - transport: str = "rest", request_type=model_service.PauseModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.pause_model(request) - - def test_pause_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5496,78 +4640,6 @@ def test_pause_model_rest_flattened_error(transport: str = "rest"): ) -def test_pause_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ResumeModelRequest, - dict, - ], -) -def test_resume_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = model.Model( - name="name_value", - display_name="display_name_value", - training_state=model.Model.TrainingState.PAUSED, - serving_state=model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.resume_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == model.Model.TrainingState.PAUSED - assert response.serving_state == model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_resume_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5688,108 +4760,27 @@ def test_resume_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_resume_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_resume_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_resume_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ResumeModelRequest.pb( - model_service.ResumeModelRequest() - ) - 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 = model.Model.to_json(model.Model()) + # 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 = model.Model() - request = model_service.ResumeModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model.Model() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } - client.resume_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_resume_model_rest_bad_request( - transport: str = "rest", request_type=model_service.ResumeModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.resume_model(request) - - -def test_resume_model_rest_flattened(): - client = ModelServiceClient( - 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 = model.Model() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -5828,49 +4819,6 @@ def test_resume_model_rest_flattened_error(transport: str = "rest"): ) -def test_resume_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.DeleteModelRequest, - dict, - ], -) -def test_delete_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_model(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5987,81 +4935,6 @@ def test_delete_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" - ) as pre: - pre.assert_not_called() - pb_message = model_service.DeleteModelRequest.pb( - model_service.DeleteModelRequest() - ) - 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() - - request = model_service.DeleteModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_model_rest_bad_request( - transport: str = "rest", request_type=model_service.DeleteModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.delete_model(request) - - def test_delete_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6119,52 +4992,6 @@ def test_delete_model_rest_flattened_error(transport: str = "rest"): ) -def test_delete_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.ListModelsRequest, - dict, - ], -) -def test_list_models_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = model_service.ListModelsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_models(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListModelsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_models_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6297,108 +5124,27 @@ def test_list_models_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_models_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_list_models_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_list_models" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.ListModelsRequest.pb( - model_service.ListModelsRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = model_service.ListModelsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = model_service.ListModelsResponse.to_json( - model_service.ListModelsResponse() + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - - request = model_service.ListModelsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = model_service.ListModelsResponse() - - client.list_models( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_models_rest_bad_request( - transport: str = "rest", request_type=model_service.ListModelsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.list_models(request) - - -def test_list_models_rest_flattened(): - client = ModelServiceClient( - 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 = model_service.ListModelsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6500,167 +5246,6 @@ def test_list_models_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - model_service.UpdateModelRequest, - dict, - ], -) -def test_update_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - request_init["model"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", - "display_name": "display_name_value", - "training_state": 1, - "serving_state": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": "type__value", - "optimization_objective": "optimization_objective_value", - "periodic_tuning_state": 1, - "last_tune_time": {}, - "tuning_operation": "tuning_operation_value", - "data_state": 1, - "filtering_option": 1, - "serving_config_lists": [ - { - "serving_config_ids": [ - "serving_config_ids_value1", - "serving_config_ids_value2", - ] - } - ], - "model_features_config": { - "frequently_bought_together_config": {"context_products_type": 1} - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = model_service.UpdateModelRequest.meta.fields["model"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["model"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["model"][field])): - del request_init["model"][field][i][subfield] - else: - del request_init["model"][field][subfield] - 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 = gcr_model.Model( - name="name_value", - display_name="display_name_value", - training_state=gcr_model.Model.TrainingState.PAUSED, - serving_state=gcr_model.Model.ServingState.INACTIVE, - type_="type__value", - optimization_objective="optimization_objective_value", - periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, - tuning_operation="tuning_operation_value", - data_state=gcr_model.Model.DataState.DATA_OK, - filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_model.Model.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_model(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_model.Model) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.training_state == gcr_model.Model.TrainingState.PAUSED - assert response.serving_state == gcr_model.Model.ServingState.INACTIVE - assert response.type_ == "type__value" - assert response.optimization_objective == "optimization_objective_value" - assert ( - response.periodic_tuning_state - == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED - ) - assert response.tuning_operation == "tuning_operation_value" - assert response.data_state == gcr_model.Model.DataState.DATA_OK - assert ( - response.filtering_option - == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED - ) - - def test_update_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6778,99 +5363,16 @@ def test_update_model_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("model",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( +def test_update_model_rest_flattened(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), + transport="rest", ) - client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_update_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.UpdateModelRequest.pb( - model_service.UpdateModelRequest() - ) - 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 = gcr_model.Model.to_json(gcr_model.Model()) - request = model_service.UpdateModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_model.Model() - - client.update_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_model_rest_bad_request( - transport: str = "rest", request_type=model_service.UpdateModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "model": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - } - 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_model(request) - - -def test_update_model_rest_flattened(): - client = ModelServiceClient( - 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 = gcr_model.Model() + # 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 = gcr_model.Model() # get arguments that satisfy an http rule for this method sample_request = { @@ -6924,49 +5426,6 @@ def test_update_model_rest_flattened_error(transport: str = "rest"): ) -def test_update_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - model_service.TuneModelRequest, - dict, - ], -) -def test_tune_model_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.tune_model(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_tune_model_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7086,89 +5545,6 @@ def test_tune_model_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_tune_model_rest_interceptors(null_interceptor): - transport = transports.ModelServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ModelServiceRestInterceptor(), - ) - client = ModelServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ModelServiceRestInterceptor, "post_tune_model" - ) as post, mock.patch.object( - transports.ModelServiceRestInterceptor, "pre_tune_model" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = model_service.TuneModelRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.tune_model( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_tune_model_rest_bad_request( - transport: str = "rest", request_type=model_service.TuneModelRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" - } - 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.tune_model(request) - - def test_tune_model_rest_flattened(): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7226,12 +5602,6 @@ def test_tune_model_rest_flattened_error(transport: str = "rest"): ) -def test_tune_model_rest_error(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ModelServiceGrpcTransport( @@ -7284,58 +5654,2023 @@ def test_credentials_transport_error(): ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ModelServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ModelServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ModelServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ModelServiceGrpcTransport, + transports.ModelServiceGrpcAsyncIOTransport, + transports.ModelServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ModelServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + call.return_value = model.Model() + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + call.return_value = model.Model() + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + call.return_value = model.Model() + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + call.return_value = None + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + call.return_value = model_service.ListModelsResponse() + client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + call.return_value = gcr_model.Model() + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ModelServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_pause_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_resume_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_models_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_models(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + ) + await client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_tune_model_empty_call_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.tune_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ModelServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_model_rest_bad_request(request_type=model_service.CreateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.CreateModelRequest, + dict, + ], +) +def test_create_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["model"] = { + "name": "name_value", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1} + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.CreateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_create_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_create_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.CreateModelRequest.pb( + model_service.CreateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.CreateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_model_rest_bad_request(request_type=model_service.GetModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.GetModelRequest, + dict, + ], +) +def test_get_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_get_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_get_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.GetModelRequest.pb(model_service.GetModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.GetModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.get_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_pause_model_rest_bad_request(request_type=model_service.PauseModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.pause_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.PauseModelRequest, + dict, + ], +) +def test_pause_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.pause_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_pause_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_pause_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.PauseModelRequest.pb( + model_service.PauseModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.PauseModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.pause_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resume_model_rest_bad_request(request_type=model_service.ResumeModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.resume_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ResumeModelRequest, + dict, + ], +) +def test_resume_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = model.Model( + name="name_value", + display_name="display_name_value", + training_state=model.Model.TrainingState.PAUSED, + serving_state=model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.resume_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == model.Model.TrainingState.PAUSED + assert response.serving_state == model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_resume_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_resume_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ResumeModelRequest.pb( + model_service.ResumeModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model.Model.to_json(model.Model()) + req.return_value.content = return_value + + request = model_service.ResumeModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model.Model() + + client.resume_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_model_rest_bad_request(request_type=model_service.DeleteModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.DeleteModelRequest, + dict, + ], +) +def test_delete_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_model(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "pre_delete_model" + ) as pre: + pre.assert_not_called() + pb_message = model_service.DeleteModelRequest.pb( + model_service.DeleteModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = model_service.DeleteModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_models_rest_bad_request(request_type=model_service.ListModelsRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_models(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.ListModelsRequest, + dict, + ], +) +def test_list_models_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = model_service.ListModelsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = model_service.ListModelsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_models(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListModelsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_models_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_list_models" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_list_models" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.ListModelsRequest.pb( + model_service.ListModelsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = model_service.ListModelsResponse.to_json( + model_service.ListModelsResponse() + ) + req.return_value.content = return_value + + request = model_service.ListModelsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = model_service.ListModelsResponse() + + client.list_models( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_model_rest_bad_request(request_type=model_service.UpdateModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.UpdateModelRequest, + dict, + ], +) +def test_update_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "model": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + } + request_init["model"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4", + "display_name": "display_name_value", + "training_state": 1, + "serving_state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "periodic_tuning_state": 1, + "last_tune_time": {}, + "tuning_operation": "tuning_operation_value", + "data_state": 1, + "filtering_option": 1, + "serving_config_lists": [ + { + "serving_config_ids": [ + "serving_config_ids_value1", + "serving_config_ids_value2", + ] + } + ], + "model_features_config": { + "frequently_bought_together_config": {"context_products_type": 1} + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = model_service.UpdateModelRequest.meta.fields["model"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["model"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["model"][field])): + del request_init["model"][field][i][subfield] + else: + del request_init["model"][field][subfield] + 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 = gcr_model.Model( + name="name_value", + display_name="display_name_value", + training_state=gcr_model.Model.TrainingState.PAUSED, + serving_state=gcr_model.Model.ServingState.INACTIVE, + type_="type__value", + optimization_objective="optimization_objective_value", + periodic_tuning_state=gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED, + tuning_operation="tuning_operation_value", + data_state=gcr_model.Model.DataState.DATA_OK, + filtering_option=common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_model.Model.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_model(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_model.Model) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.training_state == gcr_model.Model.TrainingState.PAUSED + assert response.serving_state == gcr_model.Model.ServingState.INACTIVE + assert response.type_ == "type__value" + assert response.optimization_objective == "optimization_objective_value" + assert ( + response.periodic_tuning_state + == gcr_model.Model.PeriodicTuningState.PERIODIC_TUNING_DISABLED + ) + assert response.tuning_operation == "tuning_operation_value" + assert response.data_state == gcr_model.Model.DataState.DATA_OK + assert ( + response.filtering_option + == common.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_DISABLED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(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.ModelServiceRestInterceptor, "post_update_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_update_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.UpdateModelRequest.pb( + model_service.UpdateModelRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_model.Model.to_json(gcr_model.Model()) + req.return_value.content = return_value + + request = model_service.UpdateModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_model.Model() + + client.update_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tune_model_rest_bad_request(request_type=model_service.TuneModelRequest): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.tune_model(request) + + +@pytest.mark.parametrize( + "request_type", + [ + model_service.TuneModelRequest, + dict, + ], +) +def test_tune_model_rest_call_success(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/models/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.tune_model(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tune_model_rest_interceptors(null_interceptor): + transport = transports.ModelServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ModelServiceRestInterceptor(), + ) + client = ModelServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ModelServiceRestInterceptor, "post_tune_model" + ) as post, mock.patch.object( + transports.ModelServiceRestInterceptor, "pre_tune_model" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = model_service.TuneModelRequest.pb(model_service.TuneModelRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = model_service.TuneModelRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.tune_model( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_model), "__call__") as call: + client.create_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.CreateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_model), "__call__") as call: + client.get_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.GetModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_pause_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause_model), "__call__") as call: + client.pause_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.PauseModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_resume_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume_model), "__call__") as call: + client.resume_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ResumeModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_model_empty_call_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_model), "__call__") as call: + client.delete_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.DeleteModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_models_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ModelServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_models), "__call__") as call: + client.list_models(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ModelServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.ListModelsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ModelServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_model), "__call__") as call: + client.update_model(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.UpdateModelRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_tune_model_empty_call_rest(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.tune_model), "__call__") as call: + client.tune_model(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ModelServiceGrpcTransport, - transports.ModelServiceGrpcAsyncIOTransport, - transports.ModelServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = model_service.TuneModelRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ModelServiceClient.get_transport_class(transport_name)( + +def test_model_service_rest_lro_client(): + client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7578,23 +7913,6 @@ def test_model_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_model_service_rest_lro_client(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8017,141 +8335,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ModelServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8179,7 +8362,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8234,7 +8417,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8281,7 +8464,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8324,7 +8507,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8379,7 +8562,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8426,7 +8609,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ModelServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8442,22 +8625,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ModelServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ModelServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ModelServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_prediction_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_prediction_service.py index 46fd33cf1d37..43afdd25d23c 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_prediction_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_prediction_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -38,17 +55,9 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -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.retail_v2beta.services.prediction_service import ( PredictionServiceAsyncClient, @@ -64,10 +73,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1207,25 +1230,6 @@ def test_predict(request_type, transport: str = "grpc"): assert response.validate_only is True -def test_predict_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - def test_predict_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1293,38 +1297,13 @@ def test_predict_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_predict_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.predict), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - ) - response = await client.predict() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() - - @pytest.mark.asyncio async def test_predict_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1363,7 +1342,7 @@ async def test_predict_async( transport: str = "grpc_asyncio", request_type=prediction_service.PredictRequest ): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1433,7 +1412,7 @@ def test_predict_field_headers(): @pytest.mark.asyncio async def test_predict_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1462,52 +1441,6 @@ async def test_predict_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - prediction_service.PredictRequest, - dict, - ], -) -def test_predict_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = prediction_service.PredictResponse( - attribution_token="attribution_token_value", - missing_ids=["missing_ids_value"], - validate_only=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = prediction_service.PredictResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.predict(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, prediction_service.PredictResponse) - assert response.attribution_token == "attribution_token_value" - assert response.missing_ids == ["missing_ids_value"] - assert response.validate_only is True - - def test_predict_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1634,95 +1567,6 @@ def test_predict_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_predict_rest_interceptors(null_interceptor): - transport = transports.PredictionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.PredictionServiceRestInterceptor(), - ) - client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" - ) as post, mock.patch.object( - transports.PredictionServiceRestInterceptor, "pre_predict" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = prediction_service.PredictRequest.pb( - prediction_service.PredictRequest() - ) - 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 = prediction_service.PredictResponse.to_json( - prediction_service.PredictResponse() - ) - - request = prediction_service.PredictRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = prediction_service.PredictResponse() - - client.predict( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_predict_rest_bad_request( - transport: str = "rest", request_type=prediction_service.PredictRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.predict(request) - - -def test_predict_rest_error(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PredictionServiceGrpcTransport( @@ -1815,80 +1659,430 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = PredictionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = PredictionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.PredictionServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + call.return_value = prediction_service.PredictResponse() + client.predict(request=None) -def test_prediction_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + assert args[0] == request_msg -def test_prediction_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.PredictionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "predict", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = PredictionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" - ) as Transport: +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_predict_empty_call_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + ) + await client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = PredictionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_predict_rest_bad_request(request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.predict(request) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_service.PredictRequest, + dict, + ], +) +def test_predict_rest_call_success(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = prediction_service.PredictResponse( + attribution_token="attribution_token_value", + missing_ids=["missing_ids_value"], + validate_only=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.predict(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_service.PredictResponse) + assert response.attribution_token == "attribution_token_value" + assert response.missing_ids == ["missing_ids_value"] + assert response.validate_only is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_predict_rest_interceptors(null_interceptor): + transport = transports.PredictionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.PredictionServiceRestInterceptor(), + ) + client = PredictionServiceClient(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.PredictionServiceRestInterceptor, "post_predict" + ) as post, mock.patch.object( + transports.PredictionServiceRestInterceptor, "pre_predict" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_service.PredictRequest.pb( + prediction_service.PredictRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = prediction_service.PredictResponse.to_json( + prediction_service.PredictResponse() + ) + req.return_value.content = return_value + + request = prediction_service.PredictRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_service.PredictResponse() + + client.predict( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_predict_empty_call_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.predict), "__call__") as call: + client.predict(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = prediction_service.PredictRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionServiceGrpcTransport, + ) + + +def test_prediction_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_prediction_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PredictionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "predict", + "get_operation", + "list_operations", + ) + 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_prediction_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.retail_v2beta.services.prediction_service.transports.PredictionServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionServiceTransport( @@ -2414,141 +2608,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2576,7 +2635,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2631,7 +2690,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2678,7 +2737,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2721,7 +2780,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2776,7 +2835,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2823,7 +2882,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = PredictionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -2839,22 +2898,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = PredictionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = PredictionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_product_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_product_service.py index a257812e39fe..a963877231ca 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_product_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_product_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import ( future, gapic_v1, @@ -35,7 +52,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,17 +64,9 @@ from google.oauth2 import service_account from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2beta.services.product_service import ( ProductServiceAsyncClient, @@ -71,10 +80,24 @@ from google.cloud.retail_v2beta.types import product as gcr_product +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1206,25 +1229,6 @@ def test_create_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_create_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - def test_create_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1290,46 +1294,6 @@ def test_create_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.create_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.CreateProductRequest() - - @pytest.mark.asyncio async def test_create_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1338,7 +1302,7 @@ async def test_create_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1377,7 +1341,7 @@ async def test_create_product_async( transport: str = "grpc_asyncio", request_type=product_service.CreateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1477,7 +1441,7 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1559,7 +1523,7 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1596,7 +1560,7 @@ async def test_create_product_flattened_async(): @pytest.mark.asyncio async def test_create_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1682,25 +1646,6 @@ def test_get_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_get_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - def test_get_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1764,46 +1709,6 @@ def test_get_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product.Product( - name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.get_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.GetProductRequest() - - @pytest.mark.asyncio async def test_get_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1812,7 +1717,7 @@ async def test_get_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1851,7 +1756,7 @@ async def test_get_product_async( transport: str = "grpc_asyncio", request_type=product_service.GetProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1951,7 +1856,7 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2019,7 +1924,7 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1951,7 @@ async def test_get_product_flattened_async(): @pytest.mark.asyncio async def test_get_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2094,25 +1999,6 @@ def test_list_products(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - def test_list_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2180,29 +2066,6 @@ def test_list_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - product_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.ListProductsRequest() - - @pytest.mark.asyncio async def test_list_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2211,7 +2074,7 @@ async def test_list_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2250,7 +2113,7 @@ async def test_list_products_async( transport: str = "grpc_asyncio", request_type=product_service.ListProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2316,7 +2179,7 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2386,7 +2249,7 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2415,7 +2278,7 @@ async def test_list_products_flattened_async(): @pytest.mark.asyncio async def test_list_products_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2525,7 +2388,7 @@ def test_list_products_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_products_async_pager(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2575,7 +2438,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2691,25 +2554,6 @@ def test_update_product(request_type, transport: str = "grpc"): assert response.conditions == ["conditions_value"] -def test_update_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - def test_update_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2769,46 +2613,6 @@ def test_update_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - ) - response = await client.update_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.UpdateProductRequest() - - @pytest.mark.asyncio async def test_update_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2817,7 +2621,7 @@ async def test_update_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2856,7 +2660,7 @@ async def test_update_product_async( transport: str = "grpc_asyncio", request_type=product_service.UpdateProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2956,7 +2760,7 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3033,7 +2837,7 @@ def test_update_product_flattened_error(): @pytest.mark.asyncio async def test_update_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3066,7 +2870,7 @@ async def test_update_product_flattened_async(): @pytest.mark.asyncio async def test_update_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3114,25 +2918,6 @@ def test_delete_product(request_type, transport: str = "grpc"): assert response is None -def test_delete_product_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - def test_delete_product_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3196,25 +2981,6 @@ def test_delete_product_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_product_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_product), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_product() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.DeleteProductRequest() - - @pytest.mark.asyncio async def test_delete_product_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3223,7 +2989,7 @@ async def test_delete_product_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3262,7 +3028,7 @@ async def test_delete_product_async( transport: str = "grpc_asyncio", request_type=product_service.DeleteProductRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3323,7 +3089,7 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3391,7 +3157,7 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3418,7 +3184,7 @@ async def test_delete_product_flattened_async(): @pytest.mark.asyncio async def test_delete_product_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3463,25 +3229,6 @@ def test_purge_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - def test_purge_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3552,27 +3299,6 @@ def test_purge_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.purge_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeProductsRequest() - - @pytest.mark.asyncio async def test_purge_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3581,7 +3307,7 @@ async def test_purge_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3625,7 +3351,7 @@ async def test_purge_products_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3688,7 +3414,7 @@ def test_purge_products_field_headers(): @pytest.mark.asyncio async def test_purge_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3750,25 +3476,6 @@ def test_import_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - def test_import_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3841,27 +3548,6 @@ def test_import_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.import_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportProductsRequest() - - @pytest.mark.asyncio async def test_import_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3870,7 +3556,7 @@ async def test_import_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3914,7 +3600,7 @@ async def test_import_products_async( transport: str = "grpc_asyncio", request_type=import_config.ImportProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3977,7 +3663,7 @@ def test_import_products_field_headers(): @pytest.mark.asyncio async def test_import_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4039,25 +3725,6 @@ def test_export_products(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_products_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_products), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportProductsRequest() - - def test_export_products_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4128,27 +3795,6 @@ def test_export_products_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_products_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_products), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_products() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportProductsRequest() - - @pytest.mark.asyncio async def test_export_products_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4157,7 +3803,7 @@ async def test_export_products_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4201,7 +3847,7 @@ async def test_export_products_async( transport: str = "grpc_asyncio", request_type=export_config.ExportProductsRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4264,7 +3910,7 @@ def test_export_products_field_headers(): @pytest.mark.asyncio async def test_export_products_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4326,25 +3972,6 @@ def test_set_inventory(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_set_inventory_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - def test_set_inventory_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4409,27 +4036,6 @@ def test_set_inventory_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_inventory_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.set_inventory() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.SetInventoryRequest() - - @pytest.mark.asyncio async def test_set_inventory_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4438,7 +4044,7 @@ async def test_set_inventory_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4482,7 +4088,7 @@ async def test_set_inventory_async( transport: str = "grpc_asyncio", request_type=product_service.SetInventoryRequest ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4545,7 +4151,7 @@ def test_set_inventory_field_headers(): @pytest.mark.asyncio async def test_set_inventory_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4620,7 +4226,7 @@ def test_set_inventory_flattened_error(): @pytest.mark.asyncio async def test_set_inventory_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4653,7 +4259,7 @@ async def test_set_inventory_flattened_async(): @pytest.mark.asyncio async def test_set_inventory_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4701,27 +4307,6 @@ def test_add_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - def test_add_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4799,29 +4384,6 @@ def test_add_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4830,7 +4392,7 @@ async def test_add_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4875,7 +4437,7 @@ async def test_add_fulfillment_places_async( request_type=product_service.AddFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4942,7 +4504,7 @@ def test_add_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_add_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5016,7 +4578,7 @@ def test_add_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5047,7 +4609,7 @@ async def test_add_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_add_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5094,27 +4656,6 @@ def test_remove_fulfillment_places(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_fulfillment_places_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - def test_remove_fulfillment_places_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5192,29 +4733,6 @@ def test_remove_fulfillment_places_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_fulfillment_places_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_fulfillment_places), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_fulfillment_places() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveFulfillmentPlacesRequest() - - @pytest.mark.asyncio async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5223,7 +4741,7 @@ async def test_remove_fulfillment_places_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5268,7 +4786,7 @@ async def test_remove_fulfillment_places_async( request_type=product_service.RemoveFulfillmentPlacesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5335,7 +4853,7 @@ def test_remove_fulfillment_places_field_headers(): @pytest.mark.asyncio async def test_remove_fulfillment_places_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5409,7 +4927,7 @@ def test_remove_fulfillment_places_flattened_error(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5440,7 +4958,7 @@ async def test_remove_fulfillment_places_flattened_async(): @pytest.mark.asyncio async def test_remove_fulfillment_places_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5487,27 +5005,6 @@ def test_add_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_add_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - def test_add_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5583,29 +5080,6 @@ def test_add_local_inventories_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.add_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.add_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.AddLocalInventoriesRequest() - - @pytest.mark.asyncio async def test_add_local_inventories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -5614,7 +5088,7 @@ async def test_add_local_inventories_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5659,7 +5133,7 @@ async def test_add_local_inventories_async( request_type=product_service.AddLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5726,7 +5200,7 @@ def test_add_local_inventories_field_headers(): @pytest.mark.asyncio async def test_add_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5800,7 +5274,7 @@ def test_add_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5831,7 +5305,7 @@ async def test_add_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_add_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -5878,27 +5352,6 @@ def test_remove_local_inventories(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_remove_local_inventories_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - def test_remove_local_inventories_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -5974,29 +5427,6 @@ def test_remove_local_inventories_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_local_inventories_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.remove_local_inventories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.remove_local_inventories() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == product_service.RemoveLocalInventoriesRequest() - - @pytest.mark.asyncio async def test_remove_local_inventories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -6005,7 +5435,7 @@ async def test_remove_local_inventories_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6050,7 +5480,7 @@ async def test_remove_local_inventories_async( request_type=product_service.RemoveLocalInventoriesRequest, ): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -6117,7 +5547,7 @@ def test_remove_local_inventories_field_headers(): @pytest.mark.asyncio async def test_remove_local_inventories_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6191,7 +5621,7 @@ def test_remove_local_inventories_flattened_error(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6222,7 +5652,7 @@ async def test_remove_local_inventories_flattened_async(): @pytest.mark.asyncio async def test_remove_local_inventories_flattened_error_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -6234,278 +5664,55 @@ async def test_remove_local_inventories_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - product_service.CreateProductRequest, - dict, - ], -) -def test_create_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = product_service.CreateProductRequest.meta.fields["product"] + # Ensure method has been cached + assert client._transport.create_product in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_product] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_product(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.create_product(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +def test_create_product_rest_required_fields( + request_type=product_service.CreateProductRequest, +): + transport_class = transports.ProductServiceRestTransport - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] + request_init = {} + request_init["parent"] = "" + request_init["product_id"] = "" 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - -def test_create_product_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_product] = mock_rpc - - request = {} - client.create_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_product(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_product_rest_required_fields( - request_type=product_service.CreateProductRequest, -): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["product_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped assert "productId" not in jsonified_request @@ -6601,87 +5808,6 @@ def test_create_product_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_create_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.CreateProductRequest.pb( - product_service.CreateProductRequest() - ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) - - request = product_service.CreateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() - - client.create_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_product_rest_bad_request( - transport: str = "rest", request_type=product_service.CreateProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.create_product(request) - - def test_create_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6749,88 +5875,6 @@ def test_create_product_rest_flattened_error(transport: str = "rest"): ) -def test_create_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.GetProductRequest, - dict, - ], -) -def test_get_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = product.Product( - name="name_value", - id="id_value", - type_=product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - def test_get_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6950,91 +5994,10 @@ def test_get_product_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_get_product_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_get_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.GetProductRequest.pb( - product_service.GetProductRequest() - ) - 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 = product.Product.to_json(product.Product()) - - request = product_service.GetProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product.Product() - - client.get_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_product_rest_bad_request( - transport: str = "rest", request_type=product_service.GetProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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_product(request) - - -def test_get_product_rest_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -7090,54 +6053,6 @@ def test_get_product_rest_flattened_error(transport: str = "rest"): ) -def test_get_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.ListProductsRequest, - dict, - ], -) -def test_list_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = product_service.ListProductsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = product_service.ListProductsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_products(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProductsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7276,89 +6191,6 @@ def test_list_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_list_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.ListProductsRequest.pb( - product_service.ListProductsRequest() - ) - 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 = product_service.ListProductsResponse.to_json( - product_service.ListProductsResponse() - ) - - request = product_service.ListProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = product_service.ListProductsResponse() - - client.list_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_products_rest_bad_request( - transport: str = "rest", request_type=product_service.ListProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.list_products(request) - - def test_list_products_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7483,277 +6315,52 @@ def test_list_products_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - product_service.UpdateProductRequest, - dict, - ], -) -def test_update_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - request_init["product"] = { - "expire_time": {"seconds": 751, "nanos": 543}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": ["color_families_value1", "color_families_value2"], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = product_service.UpdateProductRequest.meta.fields["product"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["product"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["product"][field])): - del request_init["product"][field][i][subfield] - else: - del request_init["product"][field][subfield] - 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 = gcr_product.Product( - name="name_value", - id="id_value", - type_=gcr_product.Product.Type.PRIMARY, - primary_product_id="primary_product_id_value", - collection_member_ids=["collection_member_ids_value"], - gtin="gtin_value", - categories=["categories_value"], - title="title_value", - brands=["brands_value"], - description="description_value", - language_code="language_code_value", - tags=["tags_value"], - availability=gcr_product.Product.Availability.IN_STOCK, - uri="uri_value", - sizes=["sizes_value"], - materials=["materials_value"], - patterns=["patterns_value"], - conditions=["conditions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_product.Product.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_product(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_product.Product) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.type_ == gcr_product.Product.Type.PRIMARY - assert response.primary_product_id == "primary_product_id_value" - assert response.collection_member_ids == ["collection_member_ids_value"] - assert response.gtin == "gtin_value" - assert response.categories == ["categories_value"] - assert response.title == "title_value" - assert response.brands == ["brands_value"] - assert response.description == "description_value" - assert response.language_code == "language_code_value" - assert response.tags == ["tags_value"] - assert response.availability == gcr_product.Product.Availability.IN_STOCK - assert response.uri == "uri_value" - assert response.sizes == ["sizes_value"] - assert response.materials == ["materials_value"] - assert response.patterns == ["patterns_value"] - assert response.conditions == ["conditions_value"] - - -def test_update_product_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_product in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_product] = mock_rpc - - request = {} - client.update_product(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_product(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_product_rest_required_fields( - request_type=product_service.UpdateProductRequest, -): - transport_class = transports.ProductServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_update_product_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_product in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_product] = mock_rpc + + request = {} + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_product(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_product_rest_required_fields( + request_type=product_service.UpdateProductRequest, +): + transport_class = transports.ProductServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) # verify fields with default values are dropped @@ -7838,91 +6445,8 @@ def test_update_product_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_update_product" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_update_product" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.UpdateProductRequest.pb( - product_service.UpdateProductRequest() - ) - 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 = gcr_product.Product.to_json(gcr_product.Product()) - - request = product_service.UpdateProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_product.Product() - - client.update_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_product_rest_bad_request( - transport: str = "rest", request_type=product_service.UpdateProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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_product(request) - - -def test_update_product_rest_flattened(): - client = ProductServiceClient( +def test_update_product_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -7988,49 +6512,6 @@ def test_update_product_rest_flattened_error(transport: str = "rest"): ) -def test_update_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.DeleteProductRequest, - dict, - ], -) -def test_delete_product_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_product(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_product_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8147,81 +6628,6 @@ def test_delete_product_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_product_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(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.ProductServiceRestInterceptor, "pre_delete_product" - ) as pre: - pre.assert_not_called() - pb_message = product_service.DeleteProductRequest.pb( - product_service.DeleteProductRequest() - ) - 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() - - request = product_service.DeleteProductRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_product( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_product_rest_bad_request( - transport: str = "rest", request_type=product_service.DeleteProductRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.delete_product(request) - - def test_delete_product_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8279,49 +6685,6 @@ def test_delete_product_rest_flattened_error(transport: str = "rest"): ) -def test_delete_product_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeProductsRequest, - dict, - ], -) -def test_purge_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_purge_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8455,134 +6818,6 @@ def test_purge_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_purge_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_purge_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeProductsRequest.pb( - purge_config.PurgeProductsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = purge_config.PurgeProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_products_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.purge_products(request) - - -def test_purge_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportProductsRequest, - dict, - ], -) -def test_import_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8712,134 +6947,6 @@ def test_import_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_import_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_import_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportProductsRequest.pb( - import_config.ImportProductsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = import_config.ImportProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_products_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.import_products(request) - - -def test_import_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportProductsRequest, - dict, - ], -) -def test_export_products_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_products(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_export_products_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -8969,143 +7076,13 @@ def test_export_products_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_products_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_export_products" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_export_products" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportProductsRequest.pb( - export_config.ExportProductsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportProductsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_products( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_products_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportProductsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" - } - 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.export_products(request) - - -def test_export_products_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.SetInventoryRequest, - dict, - ], -) -def test_set_inventory_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_inventory(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_set_inventory_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_set_inventory_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) # Should wrap all calls on client creation @@ -9215,93 +7192,6 @@ def test_set_inventory_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("inventory",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_inventory_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_set_inventory" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_set_inventory" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.SetInventoryRequest.pb( - product_service.SetInventoryRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.SetInventoryRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.set_inventory( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_inventory_rest_bad_request( - transport: str = "rest", request_type=product_service.SetInventoryRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "inventory": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - } - 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.set_inventory(request) - - def test_set_inventory_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9363,49 +7253,6 @@ def test_set_inventory_rest_flattened_error(transport: str = "rest"): ) -def test_set_inventory_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.AddFulfillmentPlacesRequest, - dict, - ], -) -def test_add_fulfillment_places_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_add_fulfillment_places_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9549,95 +7396,10 @@ def test_add_fulfillment_places_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_fulfillment_places_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_add_fulfillment_places_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_add_fulfillment_places" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_add_fulfillment_places" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.AddFulfillmentPlacesRequest.pb( - product_service.AddFulfillmentPlacesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.AddFulfillmentPlacesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.add_fulfillment_places( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.AddFulfillmentPlacesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.add_fulfillment_places(request) - - -def test_add_fulfillment_places_rest_flattened(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -9691,49 +7453,6 @@ def test_add_fulfillment_places_rest_flattened_error(transport: str = "rest"): ) -def test_add_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.RemoveFulfillmentPlacesRequest, - dict, - ], -) -def test_remove_fulfillment_places_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_fulfillment_places(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_remove_fulfillment_places_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9877,91 +7596,6 @@ def test_remove_fulfillment_places_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_fulfillment_places_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_remove_fulfillment_places" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_remove_fulfillment_places" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.RemoveFulfillmentPlacesRequest.pb( - product_service.RemoveFulfillmentPlacesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.RemoveFulfillmentPlacesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.remove_fulfillment_places( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_remove_fulfillment_places_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveFulfillmentPlacesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.remove_fulfillment_places(request) - - def test_remove_fulfillment_places_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10019,49 +7653,6 @@ def test_remove_fulfillment_places_rest_flattened_error(transport: str = "rest") ) -def test_remove_fulfillment_places_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.AddLocalInventoriesRequest, - dict, - ], -) -def test_add_local_inventories_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.add_local_inventories(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_add_local_inventories_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10196,101 +7787,16 @@ def test_add_local_inventories_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_local_inventories_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( +def test_add_local_inventories_rest_flattened(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), + transport="rest", ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_add_local_inventories" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_add_local_inventories" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.AddLocalInventoriesRequest.pb( - product_service.AddLocalInventoriesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.AddLocalInventoriesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.add_local_inventories( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_add_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.AddLocalInventoriesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.add_local_inventories(request) - - -def test_add_local_inventories_rest_flattened(): - client = ProductServiceClient( - 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 = operations_pb2.Operation(name="operations/spam") + # 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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -10338,49 +7844,6 @@ def test_add_local_inventories_rest_flattened_error(transport: str = "rest"): ) -def test_add_local_inventories_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - product_service.RemoveLocalInventoriesRequest, - dict, - ], -) -def test_remove_local_inventories_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.remove_local_inventories(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_remove_local_inventories_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -10519,91 +7982,6 @@ def test_remove_local_inventories_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_remove_local_inventories_rest_interceptors(null_interceptor): - transport = transports.ProductServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProductServiceRestInterceptor(), - ) - client = ProductServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ProductServiceRestInterceptor, "post_remove_local_inventories" - ) as post, mock.patch.object( - transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = product_service.RemoveLocalInventoriesRequest.pb( - product_service.RemoveLocalInventoriesRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = product_service.RemoveLocalInventoriesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.remove_local_inventories( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_remove_local_inventories_rest_bad_request( - transport: str = "rest", request_type=product_service.RemoveLocalInventoriesRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" - } - 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.remove_local_inventories(request) - - def test_remove_local_inventories_rest_flattened(): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10661,12 +8039,6 @@ def test_remove_local_inventories_rest_flattened_error(transport: str = "rest"): ) -def test_remove_local_inventories_rest_error(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProductServiceGrpcTransport( @@ -10708,69 +8080,3136 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.ProductServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProductServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductServiceGrpcTransport, + transports.ProductServiceGrpcAsyncIOTransport, + transports.ProductServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProductServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + call.return_value = product.Product() + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + call.return_value = product_service.ListProductsResponse() + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + call.return_value = gcr_product.Product() + client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + call.return_value = None + client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_products_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProductServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + ) + await client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_product_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_products_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_inventory_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_fulfillment_places_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_local_inventories_empty_call_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.remove_local_inventories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProductServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_product_rest_bad_request( + request_type=product_service.CreateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.CreateProductRequest, + dict, + ], +) +def test_create_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.CreateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_create_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_create_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.CreateProductRequest.pb( + product_service.CreateProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value + + request = product_service.CreateProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_product.Product() + + client.create_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_product_rest_bad_request(request_type=product_service.GetProductRequest): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.GetProductRequest, + dict, + ], +) +def test_get_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = product.Product( + name="name_value", + id="id_value", + type_=product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_get_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_get_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.GetProductRequest.pb( + product_service.GetProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product.Product.to_json(product.Product()) + req.return_value.content = return_value + + request = product_service.GetProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product.Product() + + client.get_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_products_rest_bad_request( + request_type=product_service.ListProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.ListProductsRequest, + dict, + ], +) +def test_list_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = product_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = product_service.ListProductsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_products(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_list_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_list_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.ListProductsRequest.pb( + product_service.ListProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = product_service.ListProductsResponse.to_json( + product_service.ListProductsResponse() + ) + req.return_value.content = return_value + + request = product_service.ListProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = product_service.ListProductsResponse() + + client.list_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_product_rest_bad_request( + request_type=product_service.UpdateProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.UpdateProductRequest, + dict, + ], +) +def test_update_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + request_init["product"] = { + "expire_time": {"seconds": 751, "nanos": 543}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": ["color_families_value1", "color_families_value2"], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = product_service.UpdateProductRequest.meta.fields["product"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["product"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["product"][field])): + del request_init["product"][field][i][subfield] + else: + del request_init["product"][field][subfield] + 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 = gcr_product.Product( + name="name_value", + id="id_value", + type_=gcr_product.Product.Type.PRIMARY, + primary_product_id="primary_product_id_value", + collection_member_ids=["collection_member_ids_value"], + gtin="gtin_value", + categories=["categories_value"], + title="title_value", + brands=["brands_value"], + description="description_value", + language_code="language_code_value", + tags=["tags_value"], + availability=gcr_product.Product.Availability.IN_STOCK, + uri="uri_value", + sizes=["sizes_value"], + materials=["materials_value"], + patterns=["patterns_value"], + conditions=["conditions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_product.Product.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_product(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_product.Product) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == gcr_product.Product.Type.PRIMARY + assert response.primary_product_id == "primary_product_id_value" + assert response.collection_member_ids == ["collection_member_ids_value"] + assert response.gtin == "gtin_value" + assert response.categories == ["categories_value"] + assert response.title == "title_value" + assert response.brands == ["brands_value"] + assert response.description == "description_value" + assert response.language_code == "language_code_value" + assert response.tags == ["tags_value"] + assert response.availability == gcr_product.Product.Availability.IN_STOCK + assert response.uri == "uri_value" + assert response.sizes == ["sizes_value"] + assert response.materials == ["materials_value"] + assert response.patterns == ["patterns_value"] + assert response.conditions == ["conditions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "post_update_product" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_update_product" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.UpdateProductRequest.pb( + product_service.UpdateProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_product.Product.to_json(gcr_product.Product()) + req.return_value.content = return_value + + request = product_service.UpdateProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_product.Product() + + client.update_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_product_rest_bad_request( + request_type=product_service.DeleteProductRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_product(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.DeleteProductRequest, + dict, + ], +) +def test_delete_product_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_product(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_product_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(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.ProductServiceRestInterceptor, "pre_delete_product" + ) as pre: + pre.assert_not_called() + pb_message = product_service.DeleteProductRequest.pb( + product_service.DeleteProductRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = product_service.DeleteProductRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_purge_products_rest_bad_request( + request_type=purge_config.PurgeProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeProductsRequest, + dict, + ], +) +def test_purge_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_products(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_purge_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_purge_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeProductsRequest.pb( + purge_config.PurgeProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = purge_config.PurgeProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_products_rest_bad_request( + request_type=import_config.ImportProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportProductsRequest, + dict, + ], +) +def test_import_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_products(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_import_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_import_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportProductsRequest.pb( + import_config.ImportProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = import_config.ImportProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_products_rest_bad_request( + request_type=export_config.ExportProductsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_products(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportProductsRequest, + dict, + ], +) +def test_export_products_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_products(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_products_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_export_products" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_export_products" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportProductsRequest.pb( + export_config.ExportProductsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportProductsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_products( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_inventory_rest_bad_request( + request_type=product_service.SetInventoryRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_inventory(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.SetInventoryRequest, + dict, + ], +) +def test_set_inventory_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "inventory": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_inventory(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_inventory_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_set_inventory" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_set_inventory" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.SetInventoryRequest.pb( + product_service.SetInventoryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.SetInventoryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.set_inventory( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_fulfillment_places_rest_bad_request( + request_type=product_service.AddFulfillmentPlacesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_fulfillment_places(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.AddFulfillmentPlacesRequest, + dict, + ], +) +def test_add_fulfillment_places_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_fulfillment_places(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_fulfillment_places_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_add_fulfillment_places" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_add_fulfillment_places" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.AddFulfillmentPlacesRequest.pb( + product_service.AddFulfillmentPlacesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.AddFulfillmentPlacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_fulfillment_places( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_fulfillment_places_rest_bad_request( + request_type=product_service.RemoveFulfillmentPlacesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_fulfillment_places(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.RemoveFulfillmentPlacesRequest, + dict, + ], +) +def test_remove_fulfillment_places_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_fulfillment_places(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_fulfillment_places_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_remove_fulfillment_places" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_remove_fulfillment_places" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.RemoveFulfillmentPlacesRequest.pb( + product_service.RemoveFulfillmentPlacesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.RemoveFulfillmentPlacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_fulfillment_places( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_add_local_inventories_rest_bad_request( + request_type=product_service.AddLocalInventoriesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.add_local_inventories(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.AddLocalInventoriesRequest, + dict, + ], +) +def test_add_local_inventories_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.add_local_inventories(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_local_inventories_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_add_local_inventories" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_add_local_inventories" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.AddLocalInventoriesRequest.pb( + product_service.AddLocalInventoriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.AddLocalInventoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.add_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_remove_local_inventories_rest_bad_request( + request_type=product_service.RemoveLocalInventoriesRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_local_inventories(request) + + +@pytest.mark.parametrize( + "request_type", + [ + product_service.RemoveLocalInventoriesRequest, + dict, + ], +) +def test_remove_local_inventories_rest_call_success(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "product": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/products/sample5" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_local_inventories(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_local_inventories_rest_interceptors(null_interceptor): + transport = transports.ProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProductServiceRestInterceptor(), + ) + client = ProductServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ProductServiceRestInterceptor, "post_remove_local_inventories" + ) as post, mock.patch.object( + transports.ProductServiceRestInterceptor, "pre_remove_local_inventories" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = product_service.RemoveLocalInventoriesRequest.pb( + product_service.RemoveLocalInventoriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = product_service.RemoveLocalInventoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.remove_local_inventories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_product), "__call__") as call: + client.create_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.CreateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_product), "__call__") as call: + client.get_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.GetProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_products), "__call__") as call: + client.list_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.ListProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_product), "__call__") as call: + client.update_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.UpdateProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_product_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_product), "__call__") as call: + client.delete_product(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.DeleteProductRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.purge_products), "__call__") as call: + client.purge_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_products), "__call__") as call: + client.import_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_products_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_products), "__call__") as call: + client.export_products(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportProductsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_inventory_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_inventory), "__call__") as call: + client.set_inventory(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.SetInventoryRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_fulfillment_places), "__call__" + ) as call: + client.add_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_fulfillment_places_empty_call_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_fulfillment_places), "__call__" + ) as call: + client.remove_fulfillment_places(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveFulfillmentPlacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProductServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_local_inventories), "__call__" + ) as call: + client.add_local_inventories(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProductServiceClient(transport=transport) - assert client.transport is transport + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.AddLocalInventoriesRequest() + assert args[0] == request_msg -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProductServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - transport = transports.ProductServiceGrpcAsyncIOTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_local_inventories_empty_call_rest(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_local_inventories), "__call__" + ) as call: + client.remove_local_inventories(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProductServiceGrpcTransport, - transports.ProductServiceGrpcAsyncIOTransport, - transports.ProductServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = product_service.RemoveLocalInventoriesRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProductServiceClient.get_transport_class(transport_name)( + +def test_product_service_rest_lro_client(): + client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -11021,23 +11460,6 @@ def test_product_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_product_service_rest_lro_client(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -11491,141 +11913,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11653,7 +11940,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11708,7 +11995,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11755,7 +12042,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -11798,7 +12085,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -11853,7 +12140,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -11900,7 +12187,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ProductServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -11916,22 +12203,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProductServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProductServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_project_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_project_service.py index af942ae80891..a08ad8dc6698 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_project_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_project_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2beta.services.project_service import ( ProjectServiceAsyncClient, @@ -54,10 +63,24 @@ from google.cloud.retail_v2beta.types import project, project_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1155,25 +1178,6 @@ def test_get_alert_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_get_alert_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetAlertConfigRequest() - - def test_get_alert_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1239,29 +1243,6 @@ def test_get_alert_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_alert_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.AlertConfig( - name="name_value", - ) - ) - response = await client.get_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.GetAlertConfigRequest() - - @pytest.mark.asyncio async def test_get_alert_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1270,7 +1251,7 @@ async def test_get_alert_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1309,7 +1290,7 @@ async def test_get_alert_config_async( transport: str = "grpc_asyncio", request_type=project_service.GetAlertConfigRequest ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1375,7 +1356,7 @@ def test_get_alert_config_field_headers(): @pytest.mark.asyncio async def test_get_alert_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1443,7 +1424,7 @@ def test_get_alert_config_flattened_error(): @pytest.mark.asyncio async def test_get_alert_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1470,7 +1451,7 @@ async def test_get_alert_config_flattened_async(): @pytest.mark.asyncio async def test_get_alert_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1520,27 +1501,6 @@ def test_update_alert_config(request_type, transport: str = "grpc"): assert response.name == "name_value" -def test_update_alert_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_alert_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateAlertConfigRequest() - - def test_update_alert_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1606,31 +1566,6 @@ def test_update_alert_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_alert_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_alert_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - project.AlertConfig( - name="name_value", - ) - ) - response = await client.update_alert_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == project_service.UpdateAlertConfigRequest() - - @pytest.mark.asyncio async def test_update_alert_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1639,7 +1574,7 @@ async def test_update_alert_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1679,7 +1614,7 @@ async def test_update_alert_config_async( request_type=project_service.UpdateAlertConfigRequest, ): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1749,7 +1684,7 @@ def test_update_alert_config_field_headers(): @pytest.mark.asyncio async def test_update_alert_config_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1826,7 +1761,7 @@ def test_update_alert_config_flattened_error(): @pytest.mark.asyncio async def test_update_alert_config_flattened_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1859,7 +1794,7 @@ async def test_update_alert_config_flattened_async(): @pytest.mark.asyncio async def test_update_alert_config_flattened_error_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1872,46 +1807,6 @@ async def test_update_alert_config_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - project_service.GetAlertConfigRequest, - dict, - ], -) -def test_get_alert_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/alertConfig"} - 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 = project.AlertConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.AlertConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_alert_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.AlertConfig) - assert response.name == "name_value" - - def test_get_alert_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2033,85 +1928,6 @@ def test_get_alert_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_alert_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_alert_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_get_alert_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.GetAlertConfigRequest.pb( - project_service.GetAlertConfigRequest() - ) - 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 = project.AlertConfig.to_json(project.AlertConfig()) - - request = project_service.GetAlertConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.AlertConfig() - - client.get_alert_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_alert_config_rest_bad_request( - transport: str = "rest", request_type=project_service.GetAlertConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/alertConfig"} - 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_alert_config(request) - - def test_get_alert_config_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2167,146 +1983,23 @@ def test_get_alert_config_rest_flattened_error(transport: str = "rest"): ) -def test_get_alert_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_update_alert_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - project_service.UpdateAlertConfigRequest, - dict, - ], -) -def test_update_alert_config_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} - request_init["alert_config"] = { - "name": "projects/sample1/alertConfig", - "alert_policies": [ - { - "alert_group": "alert_group_value", - "enroll_status": 1, - "recipients": [{"email_address": "email_address_value"}], - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = project_service.UpdateAlertConfigRequest.meta.fields["alert_config"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["alert_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["alert_config"][field])): - del request_init["alert_config"][field][i][subfield] - else: - del request_init["alert_config"][field][subfield] - 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 = project.AlertConfig( - name="name_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = project.AlertConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_alert_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, project.AlertConfig) - assert response.name == "name_value" - - -def test_update_alert_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.update_alert_config in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.update_alert_config in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -2411,85 +2104,6 @@ def test_update_alert_config_rest_unset_required_fields(): assert set(unset_fields) == (set(("updateMask",)) & set(("alertConfig",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_alert_config_rest_interceptors(null_interceptor): - transport = transports.ProjectServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ProjectServiceRestInterceptor(), - ) - client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_alert_config" - ) as post, mock.patch.object( - transports.ProjectServiceRestInterceptor, "pre_update_alert_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = project_service.UpdateAlertConfigRequest.pb( - project_service.UpdateAlertConfigRequest() - ) - 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 = project.AlertConfig.to_json(project.AlertConfig()) - - request = project_service.UpdateAlertConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = project.AlertConfig() - - client.update_alert_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_alert_config_rest_bad_request( - transport: str = "rest", request_type=project_service.UpdateAlertConfigRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} - 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_alert_config(request) - - def test_update_alert_config_rest_flattened(): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2549,12 +2163,6 @@ def test_update_alert_config_rest_flattened_error(transport: str = "rest"): ) -def test_update_alert_config_rest_error(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProjectServiceGrpcTransport( @@ -2596,69 +2204,679 @@ def test_credentials_transport_error(): client_options=options, credentials=ga_credentials.AnonymousCredentials() ) - # It is an error to provide scopes and a transport instance. - transport = transports.ProjectServiceGrpcTransport( + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProjectServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectServiceGrpcTransport, + transports.ProjectServiceGrpcAsyncIOTransport, + transports.ProjectServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ProjectServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_alert_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + call.return_value = project.AlertConfig() + client.get_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_alert_config_empty_call_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + call.return_value = project.AlertConfig() + client.update_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProjectServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_alert_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.AlertConfig( + name="name_value", + ) + ) + await client.get_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_alert_config_empty_call_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + project.AlertConfig( + name="name_value", + ) + ) + await client.update_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProjectServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_alert_config_rest_bad_request( + request_type=project_service.GetAlertConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/alertConfig"} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_alert_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.GetAlertConfigRequest, + dict, + ], +) +def test_get_alert_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/alertConfig"} + 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 = project.AlertConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.AlertConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_alert_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.AlertConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_alert_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_get_alert_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_get_alert_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.GetAlertConfigRequest.pb( + project_service.GetAlertConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.AlertConfig.to_json(project.AlertConfig()) + req.return_value.content = return_value + + request = project_service.GetAlertConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.AlertConfig() + + client.get_alert_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_alert_config_rest_bad_request( + request_type=project_service.UpdateAlertConfigRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_alert_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + project_service.UpdateAlertConfigRequest, + dict, + ], +) +def test_update_alert_config_rest_call_success(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"alert_config": {"name": "projects/sample1/alertConfig"}} + request_init["alert_config"] = { + "name": "projects/sample1/alertConfig", + "alert_policies": [ + { + "alert_group": "alert_group_value", + "enroll_status": 1, + "recipients": [{"email_address": "email_address_value"}], + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = project_service.UpdateAlertConfigRequest.meta.fields["alert_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["alert_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["alert_config"][field])): + del request_init["alert_config"][field][i][subfield] + else: + del request_init["alert_config"][field][subfield] + 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 = project.AlertConfig( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = project.AlertConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_alert_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, project.AlertConfig) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_alert_config_rest_interceptors(null_interceptor): + transport = transports.ProjectServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectServiceRestInterceptor(), + ) + client = ProjectServiceClient(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.ProjectServiceRestInterceptor, "post_update_alert_config" + ) as post, mock.patch.object( + transports.ProjectServiceRestInterceptor, "pre_update_alert_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = project_service.UpdateAlertConfigRequest.pb( + project_service.UpdateAlertConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = project.AlertConfig.to_json(project.AlertConfig()) + req.return_value.content = return_value + + request = project_service.UpdateAlertConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = project.AlertConfig() + + client.update_alert_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ProjectServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProjectServiceClient(transport=transport) - assert client.transport is transport + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProjectServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - channel = transport.grpc_channel - assert channel + assert client is not None - transport = transports.ProjectServiceGrpcAsyncIOTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_alert_config_empty_call_rest(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_alert_config), "__call__") as call: + client.get_alert_config(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ProjectServiceGrpcTransport, - transports.ProjectServiceGrpcAsyncIOTransport, - transports.ProjectServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.GetAlertConfigRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ProjectServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_alert_config_empty_call_rest(): + client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_alert_config), "__call__" + ) as call: + client.update_alert_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = project_service.UpdateAlertConfigRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -3236,141 +3454,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ProjectServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3398,7 +3481,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3453,7 +3536,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3500,7 +3583,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3543,7 +3626,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3598,7 +3681,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3645,7 +3728,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ProjectServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3661,22 +3744,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ProjectServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ProjectServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ProjectServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_search_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_search_service.py index b14a90df168a..d6eebbf4cafe 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_search_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_search_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,14 +53,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.retail_v2beta.services.search_service import ( SearchServiceAsyncClient, @@ -54,10 +63,24 @@ from google.cloud.retail_v2beta.types import common, search_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1161,25 +1184,6 @@ def test_search(request_type, transport: str = "grpc"): assert response.applied_controls == ["applied_controls_value"] -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - def test_search_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1259,41 +1263,13 @@ def test_search_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_search_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - ) - response = await client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - @pytest.mark.asyncio async def test_search_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1332,7 +1308,7 @@ async def test_search_async( transport: str = "grpc_asyncio", request_type=search_service.SearchRequest ): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1408,7 +1384,7 @@ def test_search_field_headers(): @pytest.mark.asyncio async def test_search_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1537,7 +1513,7 @@ def test_search_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_search_async_pager(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1565,7 @@ async def test_search_async_pager(): @pytest.mark.asyncio async def test_search_async_pages(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,58 +1609,6 @@ async def test_search_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - search_service.SearchRequest, - dict, - ], -) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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 = search_service.SearchResponse( - total_size=1086, - corrected_query="corrected_query_value", - attribution_token="attribution_token_value", - next_page_token="next_page_token_value", - redirect_uri="redirect_uri_value", - applied_controls=["applied_controls_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.corrected_query == "corrected_query_value" - assert response.attribution_token == "attribution_token_value" - assert response.next_page_token == "next_page_token_value" - assert response.redirect_uri == "redirect_uri_value" - assert response.applied_controls == ["applied_controls_value"] - - def test_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1815,87 +1739,6 @@ def test_search_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" - ) as post, mock.patch.object( - transports.SearchServiceRestInterceptor, "pre_search" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - 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 = search_service.SearchResponse.to_json( - search_service.SearchResponse() - ) - - request = search_service.SearchRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request( - transport: str = "rest", request_type=search_service.SearchRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" - } - 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.search(request) - - def test_search_rest_pager(transport: str = "rest"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2053,76 +1896,433 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = SearchServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + call.return_value = search_service.SearchResponse() + client.search(request=None) -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + assert args[0] == request_msg -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "search", - "get_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = SearchServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_search_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_search_empty_call_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + ) + await client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SearchServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_search_rest_bad_request(request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.search(request) + + +@pytest.mark.parametrize( + "request_type", + [ + search_service.SearchRequest, + dict, + ], +) +def test_search_rest_call_success(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "placement": "projects/sample1/locations/sample2/catalogs/sample3/placements/sample4" + } + 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 = search_service.SearchResponse( + total_size=1086, + corrected_query="corrected_query_value", + attribution_token="attribution_token_value", + next_page_token="next_page_token_value", + redirect_uri="redirect_uri_value", + applied_controls=["applied_controls_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.corrected_query == "corrected_query_value" + assert response.attribution_token == "attribution_token_value" + assert response.next_page_token == "next_page_token_value" + assert response.redirect_uri == "redirect_uri_value" + assert response.applied_controls == ["applied_controls_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(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.SearchServiceRestInterceptor, "post_search" + ) as post, mock.patch.object( + transports.SearchServiceRestInterceptor, "pre_search" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = search_service.SearchResponse.to_json( + search_service.SearchResponse() + ) + req.return_value.content = return_value + + request = search_service.SearchRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_search_empty_call_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.search), "__call__") as call: + client.search(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = search_service.SearchRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.retail_v2beta.services.search_service.transports.SearchServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search", + "get_operation", + "list_operations", + ) + 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_search_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.retail_v2beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages" @@ -2739,141 +2939,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = SearchServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2901,7 +2966,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2956,7 +3021,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3003,7 +3068,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -3046,7 +3111,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3101,7 +3166,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3148,7 +3213,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3164,22 +3229,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SearchServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_serving_config_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_serving_config_service.py index a22e87d7c8ce..b061769aface 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_serving_config_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_serving_config_service.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,14 +54,6 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore -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.retail_v2beta.services.serving_config_service import ( ServingConfigServiceAsyncClient, @@ -58,10 +67,24 @@ from google.cloud.retail_v2beta.types import serving_config_service +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1268,27 +1291,6 @@ def test_create_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_create_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - def test_create_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1361,48 +1363,6 @@ def test_create_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.create_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.CreateServingConfigRequest() - - @pytest.mark.asyncio async def test_create_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1411,7 +1371,7 @@ async def test_create_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1451,7 +1411,7 @@ async def test_create_serving_config_async( request_type=serving_config_service.CreateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1560,7 +1520,7 @@ def test_create_serving_config_field_headers(): @pytest.mark.asyncio async def test_create_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1644,7 +1604,7 @@ def test_create_serving_config_flattened_error(): @pytest.mark.asyncio async def test_create_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1683,7 +1643,7 @@ async def test_create_serving_config_flattened_async(): @pytest.mark.asyncio async def test_create_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1732,27 +1692,6 @@ def test_delete_serving_config(request_type, transport: str = "grpc"): assert response is None -def test_delete_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - def test_delete_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1823,27 +1762,6 @@ def test_delete_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.DeleteServingConfigRequest() - - @pytest.mark.asyncio async def test_delete_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1852,7 +1770,7 @@ async def test_delete_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1892,7 +1810,7 @@ async def test_delete_serving_config_async( request_type=serving_config_service.DeleteServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1957,7 +1875,7 @@ def test_delete_serving_config_field_headers(): @pytest.mark.asyncio async def test_delete_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2029,7 +1947,7 @@ def test_delete_serving_config_flattened_error(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2058,7 +1976,7 @@ async def test_delete_serving_config_flattened_async(): @pytest.mark.asyncio async def test_delete_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2147,27 +2065,6 @@ def test_update_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_update_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - def test_update_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2234,48 +2131,6 @@ def test_update_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.update_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.UpdateServingConfigRequest() - - @pytest.mark.asyncio async def test_update_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2284,7 +2139,7 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2324,7 +2179,7 @@ async def test_update_serving_config_async( request_type=serving_config_service.UpdateServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2433,7 +2288,7 @@ def test_update_serving_config_field_headers(): @pytest.mark.asyncio async def test_update_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2512,7 +2367,7 @@ def test_update_serving_config_flattened_error(): @pytest.mark.asyncio async def test_update_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2547,7 +2402,7 @@ async def test_update_serving_config_flattened_async(): @pytest.mark.asyncio async def test_update_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2637,27 +2492,6 @@ def test_get_serving_config(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_get_serving_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - def test_get_serving_config_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2727,48 +2561,6 @@ def test_get_serving_config_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_serving_config_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_serving_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.get_serving_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.GetServingConfigRequest() - - @pytest.mark.asyncio async def test_get_serving_config_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2777,7 +2569,7 @@ async def test_get_serving_config_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2817,7 +2609,7 @@ async def test_get_serving_config_async( request_type=serving_config_service.GetServingConfigRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2926,7 +2718,7 @@ def test_get_serving_config_field_headers(): @pytest.mark.asyncio async def test_get_serving_config_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3000,7 +2792,7 @@ def test_get_serving_config_flattened_error(): @pytest.mark.asyncio async def test_get_serving_config_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3031,7 +2823,7 @@ async def test_get_serving_config_flattened_async(): @pytest.mark.asyncio async def test_get_serving_config_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3081,27 +2873,6 @@ def test_list_serving_configs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_serving_configs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - def test_list_serving_configs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3173,31 +2944,6 @@ def test_list_serving_configs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_serving_configs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_serving_configs), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_serving_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.ListServingConfigsRequest() - - @pytest.mark.asyncio async def test_list_serving_configs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3206,7 +2952,7 @@ async def test_list_serving_configs_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3246,7 +2992,7 @@ async def test_list_serving_configs_async( request_type=serving_config_service.ListServingConfigsRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3316,7 +3062,7 @@ def test_list_serving_configs_field_headers(): @pytest.mark.asyncio async def test_list_serving_configs_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3390,7 +3136,7 @@ def test_list_serving_configs_flattened_error(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3421,7 +3167,7 @@ async def test_list_serving_configs_flattened_async(): @pytest.mark.asyncio async def test_list_serving_configs_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3535,7 +3281,7 @@ def test_list_serving_configs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_serving_configs_async_pager(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3587,7 +3333,7 @@ async def test_list_serving_configs_async_pager(): @pytest.mark.asyncio async def test_list_serving_configs_async_pages(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3710,25 +3456,6 @@ def test_add_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - def test_add_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3794,46 +3521,6 @@ def test_add_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_add_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.add_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.add_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.AddControlRequest() - - @pytest.mark.asyncio async def test_add_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3842,7 +3529,7 @@ async def test_add_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3882,7 +3569,7 @@ async def test_add_control_async( request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3987,7 +3674,7 @@ def test_add_control_field_headers(): @pytest.mark.asyncio async def test_add_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4057,7 +3744,7 @@ def test_add_control_flattened_error(): @pytest.mark.asyncio async def test_add_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4086,7 +3773,7 @@ async def test_add_control_flattened_async(): @pytest.mark.asyncio async def test_add_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4173,25 +3860,6 @@ def test_remove_control(request_type, transport: str = "grpc"): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - def test_remove_control_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4257,46 +3925,6 @@ def test_remove_control_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_remove_control_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.remove_control), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - ) - response = await client.remove_control() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == serving_config_service.RemoveControlRequest() - - @pytest.mark.asyncio async def test_remove_control_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4305,7 +3933,7 @@ async def test_remove_control_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4345,7 +3973,7 @@ async def test_remove_control_async( request_type=serving_config_service.RemoveControlRequest, ): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4450,7 +4078,7 @@ def test_remove_control_field_headers(): @pytest.mark.asyncio async def test_remove_control_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4520,7 +4148,7 @@ def test_remove_control_flattened_error(): @pytest.mark.asyncio async def test_remove_control_flattened_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4549,7 +4177,7 @@ async def test_remove_control_flattened_async(): @pytest.mark.asyncio async def test_remove_control_flattened_error_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -4561,236 +4189,45 @@ async def test_remove_control_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.CreateServingConfigRequest, - dict, - ], -) -def test_create_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["serving_config"] = { - "name": "name_value", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ - "serving_config" - ] + # Ensure method has been cached + assert ( + client._transport.create_serving_config + in client._transport._wrapped_methods + ) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_serving_config + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.create_serving_config(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.create_serving_config(request) - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - - -def test_create_serving_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_serving_config - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_serving_config - ] = mock_rpc - - request = {} - client.create_serving_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_serving_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 def test_create_serving_config_rest_required_fields( @@ -4901,88 +4338,6 @@ def test_create_serving_config_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.CreateServingConfigRequest.pb( - serving_config_service.CreateServingConfigRequest() - ) - 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 = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() - ) - - request = serving_config_service.CreateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() - - client.create_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.CreateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.create_serving_config(request) - - def test_create_serving_config_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5046,49 +4401,6 @@ def test_create_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_create_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.DeleteServingConfigRequest, - dict, - ], -) -def test_delete_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_serving_config(request) - - # Establish that the response is the type that we expect. - assert response is None - - def test_delete_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5210,84 +4522,8 @@ def test_delete_serving_config_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), - ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" - ) as pre: - pre.assert_not_called() - pb_message = serving_config_service.DeleteServingConfigRequest.pb( - serving_config_service.DeleteServingConfigRequest() - ) - 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() - - request = serving_config_service.DeleteServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - - -def test_delete_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.DeleteServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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.delete_serving_config(request) - - -def test_delete_serving_config_rest_flattened(): - client = ServingConfigServiceClient( +def test_delete_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) @@ -5343,168 +4579,152 @@ def test_delete_serving_config_rest_flattened_error(transport: str = "rest"): ) -def test_delete_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +def test_update_serving_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_serving_config + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_serving_config + ] = mock_rpc + + request = {} + client.update_serving_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_serving_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_serving_config_rest_required_fields( + request_type=serving_config_service.UpdateServingConfigRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_serving_config._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_serving_config._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 -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.UpdateServingConfigRequest, - dict, - ], -) -def test_update_serving_config_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request = request_type(**request_init) - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - request_init["serving_config"] = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", - "display_name": "display_name_value", - "model_id": "model_id_value", - "price_reranking_level": "price_reranking_level_value", - "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], - "dynamic_facet_spec": {"mode": 1}, - "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], - "filter_control_ids": [ - "filter_control_ids_value1", - "filter_control_ids_value2", - ], - "redirect_control_ids": [ - "redirect_control_ids_value1", - "redirect_control_ids_value2", - ], - "twoway_synonyms_control_ids": [ - "twoway_synonyms_control_ids_value1", - "twoway_synonyms_control_ids_value2", - ], - "oneway_synonyms_control_ids": [ - "oneway_synonyms_control_ids_value1", - "oneway_synonyms_control_ids_value2", - ], - "do_not_associate_control_ids": [ - "do_not_associate_control_ids_value1", - "do_not_associate_control_ids_value2", - ], - "replacement_control_ids": [ - "replacement_control_ids_value1", - "replacement_control_ids_value2", - ], - "ignore_control_ids": [ - "ignore_control_ids_value1", - "ignore_control_ids_value2", - ], - "diversity_level": "diversity_level_value", - "diversity_type": 2, - "enable_category_filter_level": "enable_category_filter_level_value", - "ignore_recs_denylist": True, - "personalization_spec": {"mode": 1}, - "solution_types": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 - # Determine if the message type is proto-plus or protobuf - test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ - "serving_config" - ] + response_value = Response() + response_value.status_code = 200 - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + response = client.update_serving_config(request) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["serving_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_serving_config_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + unset_fields = transport.update_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["serving_config"][field])): - del request_init["serving_config"][field][i][subfield] - else: - del request_init["serving_config"][field][subfield] - request = request_type(**request_init) + +def test_update_serving_config_rest_flattened(): + client = ServingConfigServiceClient( + 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 = gcr_serving_config.ServingConfig( - name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + return_value = gcr_serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + serving_config=gcr_serving_config.ServingConfig(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() @@ -5512,39 +4732,39 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) - # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + client.update_serving_config(**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/v2beta/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_serving_config_rest_flattened_error(transport: str = "rest"): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_serving_config( + serving_config_service.UpdateServingConfigRequest(), + serving_config=gcr_serving_config.ServingConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_update_serving_config_rest_use_cached_wrapped_rpc(): +def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5559,8 +4779,7 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_serving_config - in client._transport._wrapped_methods + client._transport.get_serving_config in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5569,28 +4788,29 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_serving_config + client._transport.get_serving_config ] = mock_rpc request = {} - client.update_serving_config(request) + client.get_serving_config(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_serving_config(request) + client.get_serving_config(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_serving_config_rest_required_fields( - request_type=serving_config_service.UpdateServingConfigRequest, +def test_get_serving_config_rest_required_fields( + request_type=serving_config_service.GetServingConfigRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5601,19 +4821,21 @@ def test_update_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_serving_config._get_unset_required_fields(jsonified_request) + ).get_serving_config._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() - ).update_serving_config._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",)) + ).get_serving_config._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 = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5622,7 +4844,7 @@ def test_update_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() + return_value = serving_config.ServingConfig() # 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 @@ -5634,172 +4856,82 @@ def test_update_serving_config_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_serving_config(request) + response = client.get_serving_config(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_serving_config_rest_unset_required_fields(): +def test_get_serving_config_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("servingConfig",))) + unset_fields = transport.get_serving_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_get_serving_config_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.UpdateServingConfigRequest.pb( - serving_config_service.UpdateServingConfigRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, + + # 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 = serving_config.ServingConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - request = serving_config_service.UpdateServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.update_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.get_serving_config(**mock_args) - pre.assert_called_once() - post.assert_called_once() + # 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/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + % client.transport._host, + args[1], + ) -def test_update_serving_config_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.UpdateServingConfigRequest, -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - 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_serving_config(request) - - -def test_update_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config=gcr_serving_config.ServingConfig(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 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_serving_config(**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/v2beta/{serving_config.name=projects/*/locations/*/catalogs/*/servingConfigs/*}" - % client.transport._host, - args[1], - ) - - -def test_update_serving_config_rest_flattened_error(transport: str = "rest"): +def test_get_serving_config_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5808,101 +4940,13 @@ def test_update_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_serving_config( - serving_config_service.UpdateServingConfigRequest(), - serving_config=gcr_serving_config.ServingConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.GetServingConfigRequest, - dict, - ], -) -def test_get_serving_config_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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 = serving_config.ServingConfig( + client.get_serving_config( + serving_config_service.GetServingConfigRequest(), name="name_value", - display_name="display_name_value", - model_id="model_id_value", - price_reranking_level="price_reranking_level_value", - facet_control_ids=["facet_control_ids_value"], - boost_control_ids=["boost_control_ids_value"], - filter_control_ids=["filter_control_ids_value"], - redirect_control_ids=["redirect_control_ids_value"], - twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], - oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], - do_not_associate_control_ids=["do_not_associate_control_ids_value"], - replacement_control_ids=["replacement_control_ids_value"], - ignore_control_ids=["ignore_control_ids_value"], - diversity_level="diversity_level_value", - diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, - enable_category_filter_level="enable_category_filter_level_value", - ignore_recs_denylist=True, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_serving_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, serving_config.ServingConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.model_id == "model_id_value" - assert response.price_reranking_level == "price_reranking_level_value" - assert response.facet_control_ids == ["facet_control_ids_value"] - assert response.boost_control_ids == ["boost_control_ids_value"] - assert response.filter_control_ids == ["filter_control_ids_value"] - assert response.redirect_control_ids == ["redirect_control_ids_value"] - assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] - assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] - assert response.do_not_associate_control_ids == [ - "do_not_associate_control_ids_value" - ] - assert response.replacement_control_ids == ["replacement_control_ids_value"] - assert response.ignore_control_ids == ["ignore_control_ids_value"] - assert response.diversity_level == "diversity_level_value" - assert ( - response.diversity_type - == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY - ) - assert response.enable_category_filter_level == "enable_category_filter_level_value" - assert response.ignore_recs_denylist is True - assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - -def test_get_serving_config_rest_use_cached_wrapped_rpc(): +def test_list_serving_configs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5917,7 +4961,7 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_serving_config in client._transport._wrapped_methods + client._transport.list_serving_configs in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5926,29 +4970,29 @@ def test_get_serving_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_serving_config + client._transport.list_serving_configs ] = mock_rpc request = {} - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_serving_config(request) + client.list_serving_configs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_serving_config_rest_required_fields( - request_type=serving_config_service.GetServingConfigRequest, +def test_list_serving_configs_rest_required_fields( + request_type=serving_config_service.ListServingConfigsRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5959,21 +5003,28 @@ def test_get_serving_config_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_serving_config._get_unset_required_fields(jsonified_request) + ).list_serving_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) 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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5982,7 +5033,7 @@ def test_get_serving_config_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse() # 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 @@ -6003,130 +5054,57 @@ def test_get_serving_config_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_serving_config(request) + response = client.list_serving_configs(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_serving_config_rest_unset_required_fields(): +def test_list_serving_configs_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_serving_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_serving_config_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_list_serving_configs_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_get_serving_config" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.GetServingConfigRequest.pb( - serving_config_service.GetServingConfigRequest() - ) - 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 = serving_config.ServingConfig.to_json( - serving_config.ServingConfig() - ) - - request = serving_config_service.GetServingConfigRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config.ServingConfig() - - client.get_serving_config( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_serving_config_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.GetServingConfigRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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_serving_config(request) - - -def test_get_serving_config_rest_flattened(): - client = ServingConfigServiceClient( - 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 = serving_config.ServingConfig() + # 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 = serving_config_service.ListServingConfigsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "parent": "projects/sample1/locations/sample2/catalogs/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -6134,25 +5112,27 @@ def test_get_serving_config_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config.ServingConfig.pb(return_value) + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_serving_config(**mock_args) + client.list_serving_configs(**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/v2beta/{name=projects/*/locations/*/catalogs/*/servingConfigs/*}" + "%s/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" % client.transport._host, args[1], ) -def test_get_serving_config_rest_flattened_error(transport: str = "rest"): +def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6161,61 +5141,79 @@ def test_get_serving_config_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_serving_config( - serving_config_service.GetServingConfigRequest(), - name="name_value", + client.list_serving_configs( + serving_config_service.ListServingConfigsRequest(), + parent="parent_value", ) -def test_get_serving_config_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - serving_config_service.ListServingConfigsRequest, - dict, - ], -) -def test_list_serving_configs_rest(request_type): +def test_list_serving_configs_rest_pager(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = serving_config_service.ListServingConfigsResponse( - next_page_token="next_page_token_value", + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + next_page_token="abc", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[], + next_page_token="def", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + ], + next_page_token="ghi", + ), + serving_config_service.ListServingConfigsResponse( + serving_configs=[ + serving_config.ServingConfig(), + serving_config.ServingConfig(), + ], + ), ) + # Two responses for two calls + response = response + response - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value + # Wrap the values into proper Response objs + response = tuple( + serving_config_service.ListServingConfigsResponse.to_json(x) + for x in response ) - json_return_value = json_format.MessageToJson(return_value) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_serving_configs(request) + sample_request = { + "parent": "projects/sample1/locations/sample2/catalogs/sample3" + } - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServingConfigsPager) - assert response.next_page_token == "next_page_token_value" + pager = client.list_serving_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, serving_config.ServingConfig) for i in results) + + pages = list(client.list_serving_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_serving_configs_rest_use_cached_wrapped_rpc(): +def test_add_control_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6229,39 +5227,36 @@ def test_list_serving_configs_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_serving_configs in client._transport._wrapped_methods - ) + assert client._transport.add_control in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_serving_configs - ] = mock_rpc + client._transport._wrapped_methods[client._transport.add_control] = mock_rpc request = {} - client.list_serving_configs(request) + client.add_control(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_serving_configs(request) + client.add_control(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_serving_configs_rest_required_fields( - request_type=serving_config_service.ListServingConfigsRequest, +def test_add_control_rest_required_fields( + request_type=serving_config_service.AddControlRequest, ): transport_class = transports.ServingConfigServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6272,28 +5267,24 @@ def test_list_serving_configs_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) + ).add_control._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" + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_serving_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).add_control._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" + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6302,7 +5293,7 @@ def test_list_serving_configs_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # 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 @@ -6314,132 +5305,238 @@ def test_list_serving_configs_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_serving_configs(request) + response = client.add_control(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_serving_configs_rest_unset_required_fields(): +def test_add_control_rest_unset_required_fields(): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_serving_configs._get_unset_required_fields({}) + unset_fields = transport.add_control._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "servingConfig", + "controlId", ) ) - & set(("parent",)) ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_serving_configs_rest_interceptors(null_interceptor): - transport = transports.ServingConfigServiceRestTransport( +def test_add_control_rest_flattened(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ServingConfigServiceRestInterceptor(), + transport="rest", ) - client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_list_serving_configs" - ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = serving_config_service.ListServingConfigsRequest.pb( - serving_config_service.ListServingConfigsRequest() - ) - 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 = ( - serving_config_service.ListServingConfigsResponse.to_json( - serving_config_service.ListServingConfigsResponse() - ) - ) + # 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 = gcr_serving_config.ServingConfig() - request = serving_config_service.ListServingConfigsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = serving_config_service.ListServingConfigsResponse() + # get arguments that satisfy an http rule for this method + sample_request = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } - client.list_serving_configs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + serving_config="serving_config_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + client.add_control(**mock_args) -def test_list_serving_configs_rest_bad_request( - transport: str = "rest", - request_type=serving_config_service.ListServingConfigsRequest, -): + # 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/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" + % client.transport._host, + args[1], + ) + + +def test_add_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_control( + serving_config_service.AddControlRequest(), + serving_config="serving_config_value", + ) + + +def test_remove_control_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_control in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + + request = {} + client.remove_control(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.remove_control(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_control_rest_required_fields( + request_type=serving_config_service.RemoveControlRequest, +): + transport_class = transports.ServingConfigServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request_init["control_id"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # 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.list_serving_configs(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_list_serving_configs_rest_flattened(): + jsonified_request["servingConfig"] = "serving_config_value" + jsonified_request["controlId"] = "control_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_control._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == "serving_config_value" + assert "controlId" in jsonified_request + assert jsonified_request["controlId"] == "control_id_value" + + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcr_serving_config.ServingConfig() + # 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 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.remove_control(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_remove_control_rest_unset_required_fields(): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.remove_control._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "servingConfig", + "controlId", + ) + ) + ) + + +def test_remove_control_rest_flattened(): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6448,16 +5545,16 @@ def test_list_serving_configs_rest_flattened(): # 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 = serving_config_service.ListServingConfigsResponse() + return_value = gcr_serving_config.ServingConfig() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + serving_config="serving_config_value", ) mock_args.update(sample_request) @@ -6465,27 +5562,25 @@ def test_list_serving_configs_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = serving_config_service.ListServingConfigsResponse.pb( - return_value - ) + return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_serving_configs(**mock_args) + client.remove_control(**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/v2beta/{parent=projects/*/locations/*/catalogs/*}/servingConfigs" + "%s/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" % client.transport._host, args[1], ) -def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): +def test_remove_control_rest_flattened_error(transport: str = "rest"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6494,101 +5589,1286 @@ def test_list_serving_configs_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_serving_configs( - serving_config_service.ListServingConfigsRequest(), - parent="parent_value", + client.remove_control( + serving_config_service.RemoveControlRequest(), + serving_config="serving_config_value", ) -def test_list_serving_configs_rest_pager(transport: str = "rest"): - client = ServingConfigServiceClient( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - next_page_token="abc", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[], - next_page_token="def", - ), - serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - ], - next_page_token="ghi", - ), + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServingConfigServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServingConfigServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServingConfigServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServingConfigServiceGrpcTransport, + transports.ServingConfigServiceGrpcAsyncIOTransport, + transports.ServingConfigServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = ServingConfigServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + call.return_value = None + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + call.return_value = gcr_serving_config.ServingConfig() + client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + call.return_value = serving_config.ServingConfig() + client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + call.return_value = serving_config_service.ListServingConfigsResponse() + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + call.return_value = gcr_serving_config.ServingConfig() + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ServingConfigServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.update_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_serving_config_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.get_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_serving_configs_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( serving_config_service.ListServingConfigsResponse( - serving_configs=[ - serving_config.ServingConfig(), - serving_config.ServingConfig(), - ], - ), + next_page_token="next_page_token_value", + ) + ) + await client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.add_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_control_empty_call_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + ) + await client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ServingConfigServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_serving_config_rest_bad_request( + request_type=serving_config_service.CreateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.CreateServingConfigRequest, + dict, + ], +) +def test_create_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["serving_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.CreateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - serving_config_service.ListServingConfigsResponse.to_json(x) - for x in response + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.CreateServingConfigRequest.pb( + serving_config_service.CreateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.CreateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.create_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_serving_config_rest_bad_request( + request_type=serving_config_service.DeleteServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.DeleteServingConfigRequest, + dict, + ], +) +def test_delete_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_serving_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "pre_delete_serving_config" + ) as pre: + pre.assert_not_called() + pb_message = serving_config_service.DeleteServingConfigRequest.pb( + serving_config_service.DeleteServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + + request = serving_config_service.DeleteServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_update_serving_config_rest_bad_request( + request_type=serving_config_service.UpdateServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_serving_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.UpdateServingConfigRequest, + dict, + ], +) +def test_update_serving_config_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "serving_config": { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + } + request_init["serving_config"] = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4", + "display_name": "display_name_value", + "model_id": "model_id_value", + "price_reranking_level": "price_reranking_level_value", + "facet_control_ids": ["facet_control_ids_value1", "facet_control_ids_value2"], + "dynamic_facet_spec": {"mode": 1}, + "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"], + "filter_control_ids": [ + "filter_control_ids_value1", + "filter_control_ids_value2", + ], + "redirect_control_ids": [ + "redirect_control_ids_value1", + "redirect_control_ids_value2", + ], + "twoway_synonyms_control_ids": [ + "twoway_synonyms_control_ids_value1", + "twoway_synonyms_control_ids_value2", + ], + "oneway_synonyms_control_ids": [ + "oneway_synonyms_control_ids_value1", + "oneway_synonyms_control_ids_value2", + ], + "do_not_associate_control_ids": [ + "do_not_associate_control_ids_value1", + "do_not_associate_control_ids_value2", + ], + "replacement_control_ids": [ + "replacement_control_ids_value1", + "replacement_control_ids_value2", + ], + "ignore_control_ids": [ + "ignore_control_ids_value1", + "ignore_control_ids_value2", + ], + "diversity_level": "diversity_level_value", + "diversity_type": 2, + "enable_category_filter_level": "enable_category_filter_level_value", + "ignore_recs_denylist": True, + "personalization_spec": {"mode": 1}, + "solution_types": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = serving_config_service.UpdateServingConfigRequest.meta.fields[ + "serving_config" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["serving_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["serving_config"][field])): + del request_init["serving_config"][field][i][subfield] + else: + del request_init["serving_config"][field][subfield] + 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/catalogs/sample3" + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_serving_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.UpdateServingConfigRequest.pb( + serving_config_service.UpdateServingConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, } - pager = client.list_serving_configs(request=sample_request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value + + request = serving_config_service.UpdateServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() + + client.update_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, serving_config.ServingConfig) for i in results) +def test_get_serving_config_rest_bad_request( + request_type=serving_config_service.GetServingConfigRequest, +): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + request = request_type(**request_init) - pages = list(client.list_serving_configs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_serving_config(request) @pytest.mark.parametrize( "request_type", [ - serving_config_service.AddControlRequest, + serving_config_service.GetServingConfigRequest, dict, ], ) -def test_add_control_rest(request_type): +def test_get_serving_config_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + "name": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" } 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 = gcr_serving_config.ServingConfig( + return_value = serving_config.ServingConfig( name="name_value", display_name="display_name_value", model_id="model_id_value", @@ -6603,25 +6883,25 @@ def test_add_control_rest(request_type): replacement_control_ids=["replacement_control_ids_value"], ignore_control_ids=["ignore_control_ids_value"], diversity_level="diversity_level_value", - diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + diversity_type=serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, enable_category_filter_level="enable_category_filter_level_value", ignore_recs_denylist=True, solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) + return_value = serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.add_control(request) + response = client.get_serving_config(request) # Establish that the response is the type that we expect. - assert isinstance(response, gcr_serving_config.ServingConfig) + assert isinstance(response, serving_config.ServingConfig) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.model_id == "model_id_value" @@ -6640,147 +6920,138 @@ def test_add_control_rest(request_type): assert response.diversity_level == "diversity_level_value" assert ( response.diversity_type - == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY + == serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) assert response.enable_category_filter_level == "enable_category_filter_level_value" assert response.ignore_recs_denylist is True assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_add_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.add_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_serving_config_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_get_serving_config" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.GetServingConfigRequest.pb( + serving_config_service.GetServingConfigRequest() ) - client._transport._wrapped_methods[client._transport.add_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.add_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = serving_config.ServingConfig.to_json( + serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.GetServingConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = serving_config.ServingConfig() - client.add_control(request) + client.get_serving_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_add_control_rest_required_fields( - request_type=serving_config_service.AddControlRequest, +def test_list_serving_configs_rest_bad_request( + request_type=serving_config_service.ListServingConfigsRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).add_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_serving_configs(request) - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.ListServingConfigsRequest, + dict, + ], +) +def test_list_serving_configs_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() # 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 - - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.add_control(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = serving_config_service.ListServingConfigsResponse( + next_page_token="next_page_token_value", + ) -def test_add_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - unset_fields = transport.add_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) + # Convert return value to protobuf type + return_value = serving_config_service.ListServingConfigsResponse.pb( + return_value ) - ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_serving_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServingConfigsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_add_control_rest_interceptors(null_interceptor): +def test_list_serving_configs_rest_interceptors(null_interceptor): transport = transports.ServingConfigServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6788,19 +7059,20 @@ def test_add_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_add_control" + transports.ServingConfigServiceRestInterceptor, "post_list_serving_configs" ) as post, mock.patch.object( - transports.ServingConfigServiceRestInterceptor, "pre_add_control" + transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = serving_config_service.AddControlRequest.pb( - serving_config_service.AddControlRequest() + pb_message = serving_config_service.ListServingConfigsRequest.pb( + serving_config_service.ListServingConfigsRequest() ) transcode.return_value = { "method": "post", @@ -6809,22 +7081,22 @@ def test_add_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( - gcr_serving_config.ServingConfig() + return_value = serving_config_service.ListServingConfigsResponse.to_json( + serving_config_service.ListServingConfigsResponse() ) + req.return_value.content = return_value - request = serving_config_service.AddControlRequest() + request = serving_config_service.ListServingConfigsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gcr_serving_config.ServingConfig() + post.return_value = serving_config_service.ListServingConfigsResponse() - client.add_control( + client.list_serving_configs( request, metadata=[ ("key", "val"), @@ -6837,13 +7109,11 @@ def test_add_control_rest_interceptors(null_interceptor): def test_add_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.AddControlRequest + request_type=serving_config_service.AddControlRequest, ): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = { "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" @@ -6855,89 +7125,25 @@ def test_add_control_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.add_control(request) -def test_add_control_rest_flattened(): - client = ServingConfigServiceClient( - 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 = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.add_control(**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/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:addControl" - % client.transport._host, - args[1], - ) - - -def test_add_control_rest_flattened_error(transport: str = "rest"): - client = ServingConfigServiceClient( - 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.add_control( - serving_config_service.AddControlRequest(), - serving_config="serving_config_value", - ) - - -def test_add_control_rest_error(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - @pytest.mark.parametrize( "request_type", [ - serving_config_service.RemoveControlRequest, + serving_config_service.AddControlRequest, dict, ], ) -def test_remove_control_rest(request_type): +def test_add_control_rest_call_success(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -6971,15 +7177,15 @@ def test_remove_control_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.remove_control(request) + response = client.add_control(request) # Establish that the response is the type that we expect. assert isinstance(response, gcr_serving_config.ServingConfig) @@ -7008,136 +7214,168 @@ def test_remove_control_rest(request_type): assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] -def test_remove_control_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.remove_control in client._transport._wrapped_methods +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_control_rest_interceptors(null_interceptor): + transport = transports.ServingConfigServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ServingConfigServiceRestInterceptor(), + ) + client = ServingConfigServiceClient(transport=transport) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "post_add_control" + ) as post, mock.patch.object( + transports.ServingConfigServiceRestInterceptor, "pre_add_control" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = serving_config_service.AddControlRequest.pb( + serving_config_service.AddControlRequest() ) - client._transport._wrapped_methods[client._transport.remove_control] = mock_rpc + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - request = {} - client.remove_control(request) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = gcr_serving_config.ServingConfig.to_json( + gcr_serving_config.ServingConfig() + ) + req.return_value.content = return_value - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + request = serving_config_service.AddControlRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_serving_config.ServingConfig() - client.remove_control(request) + client.add_control( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + pre.assert_called_once() + post.assert_called_once() -def test_remove_control_rest_required_fields( +def test_remove_control_rest_bad_request( request_type=serving_config_service.RemoveControlRequest, ): - transport_class = transports.ServingConfigServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request_init["control_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = "serving_config_value" - jsonified_request["controlId"] = "control_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).remove_control._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == "serving_config_value" - assert "controlId" in jsonified_request - assert jsonified_request["controlId"] == "control_id_value" - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.remove_control(request) - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + serving_config_service.RemoveControlRequest, + dict, + ], +) +def test_remove_control_rest_call_success(request_type): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.remove_control(request) + # send a request that will satisfy transcoding + request_init = { + "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" + } + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = gcr_serving_config.ServingConfig( + name="name_value", + display_name="display_name_value", + model_id="model_id_value", + price_reranking_level="price_reranking_level_value", + facet_control_ids=["facet_control_ids_value"], + boost_control_ids=["boost_control_ids_value"], + filter_control_ids=["filter_control_ids_value"], + redirect_control_ids=["redirect_control_ids_value"], + twoway_synonyms_control_ids=["twoway_synonyms_control_ids_value"], + oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"], + do_not_associate_control_ids=["do_not_associate_control_ids_value"], + replacement_control_ids=["replacement_control_ids_value"], + ignore_control_ids=["ignore_control_ids_value"], + diversity_level="diversity_level_value", + diversity_type=gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY, + enable_category_filter_level="enable_category_filter_level_value", + ignore_recs_denylist=True, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_remove_control_rest_unset_required_fields(): - transport = transports.ServingConfigServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = gcr_serving_config.ServingConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.remove_control(request) - unset_fields = transport.remove_control._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "servingConfig", - "controlId", - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_serving_config.ServingConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.model_id == "model_id_value" + assert response.price_reranking_level == "price_reranking_level_value" + assert response.facet_control_ids == ["facet_control_ids_value"] + assert response.boost_control_ids == ["boost_control_ids_value"] + assert response.filter_control_ids == ["filter_control_ids_value"] + assert response.redirect_control_ids == ["redirect_control_ids_value"] + assert response.twoway_synonyms_control_ids == ["twoway_synonyms_control_ids_value"] + assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"] + assert response.do_not_associate_control_ids == [ + "do_not_associate_control_ids_value" + ] + assert response.replacement_control_ids == ["replacement_control_ids_value"] + assert response.ignore_control_ids == ["ignore_control_ids_value"] + assert response.diversity_level == "diversity_level_value" + assert ( + response.diversity_type + == gcr_serving_config.ServingConfig.DiversityType.RULE_BASED_DIVERSITY ) + assert response.enable_category_filter_level == "enable_category_filter_level_value" + assert response.ignore_recs_denylist is True + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7149,6 +7387,7 @@ def test_remove_control_rest_interceptors(null_interceptor): else transports.ServingConfigServiceRestInterceptor(), ) client = ServingConfigServiceClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -7170,12 +7409,12 @@ def test_remove_control_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcr_serving_config.ServingConfig.to_json( + return_value = gcr_serving_config.ServingConfig.to_json( gcr_serving_config.ServingConfig() ) + req.return_value.content = return_value request = serving_config_service.RemoveControlRequest() metadata = [ @@ -7197,19 +7436,20 @@ def test_remove_control_rest_interceptors(null_interceptor): post.assert_called_once() -def test_remove_control_rest_bad_request( - transport: str = "rest", request_type=serving_config_service.RemoveControlRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - - # send a request that will satisfy transcoding - request_init = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - 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( @@ -7217,181 +7457,265 @@ def test_remove_control_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.remove_control(request) + client.get_operation(request) -def test_remove_control_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } + 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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = gcr_serving_config.ServingConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "serving_config": "projects/sample1/locations/sample2/catalogs/sample3/servingConfigs/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - serving_config="serving_config_value", - ) - mock_args.update(sample_request) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gcr_serving_config.ServingConfig.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value - client.remove_control(**mock_args) + response = client.get_operation(request) - # 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/v2beta/{serving_config=projects/*/locations/*/catalogs/*/servingConfigs/*}:removeControl" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_remove_control_rest_flattened_error(transport: str = "rest"): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.remove_control( - serving_config_service.RemoveControlRequest(), - serving_config="serving_config_value", - ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) -def test_remove_control_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + assert client is not None - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_serving_config), "__call__" + ) as call: + client.create_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.CreateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_serving_config), "__call__" + ) as call: + client.delete_serving_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.DeleteServingConfigRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServingConfigServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_serving_config), "__call__" + ) as call: + client.update_serving_config(request=None) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.UpdateServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_serving_config_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ServingConfigServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_serving_config), "__call__" + ) as call: + client.get_serving_config(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServingConfigServiceGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.GetServingConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_serving_configs_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ServingConfigServiceGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_serving_configs), "__call__" + ) as call: + client.list_serving_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.ListServingConfigsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_control), "__call__") as call: + client.add_control(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServingConfigServiceGrpcTransport, - transports.ServingConfigServiceGrpcAsyncIOTransport, - transports.ServingConfigServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.AddControlRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ServingConfigServiceClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_control_empty_call_rest(): + client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.remove_control), "__call__") as call: + client.remove_control(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = serving_config_service.RemoveControlRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -8028,141 +8352,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = ServingConfigServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8190,7 +8379,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8245,7 +8434,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8292,7 +8481,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8335,7 +8524,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8390,7 +8579,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8437,7 +8626,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ServingConfigServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8453,22 +8642,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ServingConfigServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ServingConfigServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ServingConfigServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_user_event_service.py b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_user_event_service.py index c1f9c3cf9491..45ca629adf86 100644 --- a/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_user_event_service.py +++ b/packages/google-cloud-retail/tests/unit/gapic/retail_v2beta/test_user_event_service.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import httpbody_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -49,17 +66,9 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import duration_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.protobuf import wrappers_pb2 # type: ignore from google.type import date_pb2 # type: ignore -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.retail_v2beta.services.user_event_service import ( UserEventServiceAsyncClient, @@ -78,10 +87,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1237,25 +1260,6 @@ def test_write_user_event(request_type, transport: str = "grpc"): assert response.entity == "entity_value" -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - def test_write_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1321,43 +1325,6 @@ def test_write_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_write_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - user_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - ) - response = await client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - @pytest.mark.asyncio async def test_write_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1366,7 +1333,7 @@ async def test_write_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1406,7 +1373,7 @@ async def test_write_user_event_async( request_type=user_event_service.WriteUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1500,7 +1467,7 @@ def test_write_user_event_field_headers(): @pytest.mark.asyncio async def test_write_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1569,27 +1536,6 @@ def test_collect_user_event(request_type, transport: str = "grpc"): assert response.data == b"data_blob" -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - def test_collect_user_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1667,32 +1613,6 @@ def test_collect_user_event_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_collect_user_event_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - ) - response = await client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - @pytest.mark.asyncio async def test_collect_user_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1701,7 +1621,7 @@ async def test_collect_user_event_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1741,7 +1661,7 @@ async def test_collect_user_event_async( request_type=user_event_service.CollectUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1813,7 +1733,7 @@ def test_collect_user_event_field_headers(): @pytest.mark.asyncio async def test_collect_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1879,27 +1799,6 @@ def test_purge_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - def test_purge_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1974,29 +1873,6 @@ def test_purge_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_purge_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - @pytest.mark.asyncio async def test_purge_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2005,7 +1881,7 @@ async def test_purge_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2049,7 +1925,7 @@ async def test_purge_user_events_async( transport: str = "grpc_asyncio", request_type=purge_config.PurgeUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2116,7 +1992,7 @@ def test_purge_user_events_field_headers(): @pytest.mark.asyncio async def test_purge_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2182,27 +2058,6 @@ def test_import_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - def test_import_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2277,29 +2132,6 @@ def test_import_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_import_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - @pytest.mark.asyncio async def test_import_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2308,7 +2140,7 @@ async def test_import_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2352,7 +2184,7 @@ async def test_import_user_events_async( transport: str = "grpc_asyncio", request_type=import_config.ImportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2419,7 +2251,7 @@ def test_import_user_events_field_headers(): @pytest.mark.asyncio async def test_import_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2485,27 +2317,6 @@ def test_export_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_export_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.export_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportUserEventsRequest() - - def test_export_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2582,29 +2393,6 @@ def test_export_user_events_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_export_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.export_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == export_config.ExportUserEventsRequest() - - @pytest.mark.asyncio async def test_export_user_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2613,7 +2401,7 @@ async def test_export_user_events_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2657,7 +2445,7 @@ async def test_export_user_events_async( transport: str = "grpc_asyncio", request_type=export_config.ExportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2724,7 +2512,7 @@ def test_export_user_events_field_headers(): @pytest.mark.asyncio async def test_export_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2790,27 +2578,6 @@ def test_rejoin_user_events(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_rejoin_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - def test_rejoin_user_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2886,39 +2653,16 @@ def test_rejoin_user_events_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_rejoin_user_events_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rejoin_user_events), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.rejoin_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.RejoinUserEventsRequest() - - -@pytest.mark.asyncio -async def test_rejoin_user_events_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +async def test_rejoin_user_events_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -2961,7 +2705,7 @@ async def test_rejoin_user_events_async( request_type=user_event_service.RejoinUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3028,7 +2772,7 @@ def test_rejoin_user_events_field_headers(): @pytest.mark.asyncio async def test_rejoin_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3059,311 +2803,51 @@ async def test_rejoin_user_events_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.WriteUserEventRequest, - dict, - ], -) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_write_user_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} - request_init["user_event"] = { - "event_type": "event_type_value", - "visitor_id": "visitor_id_value", - "session_id": "session_id_value", - "event_time": {"seconds": 751, "nanos": 543}, - "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], - "attribution_token": "attribution_token_value", - "product_details": [ - { - "product": { - "expire_time": {}, - "ttl": {"seconds": 751, "nanos": 543}, - "name": "name_value", - "id": "id_value", - "type_": 1, - "primary_product_id": "primary_product_id_value", - "collection_member_ids": [ - "collection_member_ids_value1", - "collection_member_ids_value2", - ], - "gtin": "gtin_value", - "categories": ["categories_value1", "categories_value2"], - "title": "title_value", - "brands": ["brands_value1", "brands_value2"], - "description": "description_value", - "language_code": "language_code_value", - "attributes": {}, - "tags": ["tags_value1", "tags_value2"], - "price_info": { - "currency_code": "currency_code_value", - "price": 0.531, - "original_price": 0.1479, - "cost": 0.441, - "price_effective_time": {}, - "price_expire_time": {}, - "price_range": { - "price": { - "minimum": 0.764, - "exclusive_minimum": 0.18430000000000002, - "maximum": 0.766, - "exclusive_maximum": 0.1845, - }, - "original_price": {}, - }, - }, - "rating": { - "rating_count": 1293, - "average_rating": 0.1471, - "rating_histogram": [1715, 1716], - }, - "available_time": {}, - "availability": 1, - "available_quantity": {"value": 541}, - "fulfillment_info": [ - { - "type_": "type__value", - "place_ids": ["place_ids_value1", "place_ids_value2"], - } - ], - "uri": "uri_value", - "images": [{"uri": "uri_value", "height": 633, "width": 544}], - "audience": { - "genders": ["genders_value1", "genders_value2"], - "age_groups": ["age_groups_value1", "age_groups_value2"], - }, - "color_info": { - "color_families": [ - "color_families_value1", - "color_families_value2", - ], - "colors": ["colors_value1", "colors_value2"], - }, - "sizes": ["sizes_value1", "sizes_value2"], - "materials": ["materials_value1", "materials_value2"], - "patterns": ["patterns_value1", "patterns_value2"], - "conditions": ["conditions_value1", "conditions_value2"], - "promotions": [{"promotion_id": "promotion_id_value"}], - "publish_time": {}, - "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, - "variants": {}, - "local_inventories": [ - { - "place_id": "place_id_value", - "price_info": {}, - "attributes": {}, - "fulfillment_types": [ - "fulfillment_types_value1", - "fulfillment_types_value2", - ], - } - ], - }, - "quantity": {}, - } - ], - "completion_detail": { - "completion_attribution_token": "completion_attribution_token_value", - "selected_suggestion": "selected_suggestion_value", - "selected_position": 1821, - }, - "attributes": {}, - "cart_id": "cart_id_value", - "purchase_transaction": { - "id": "id_value", - "revenue": 0.762, - "tax": 0.333, - "cost": 0.441, - "currency_code": "currency_code_value", - }, - "search_query": "search_query_value", - "filter": "filter_value", - "order_by": "order_by_value", - "offset": 647, - "page_categories": ["page_categories_value1", "page_categories_value2"], - "user_info": { - "user_id": "user_id_value", - "ip_address": "ip_address_value", - "user_agent": "user_agent_value", - "direct_user_request": True, - }, - "uri": "uri_value", - "referrer_uri": "referrer_uri_value", - "page_view_id": "page_view_id_value", - "entity": "entity_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + # Ensure method has been cached + assert client._transport.write_user_event in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.write_user_event + ] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + request = {} + client.write_user_event(request) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + client.write_user_event(request) - subfields_not_in_runtime = [] + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["user_event"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +def test_write_user_event_rest_required_fields( + request_type=user_event_service.WriteUserEventRequest, +): + transport_class = transports.UserEventServiceRestTransport - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["user_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][field][subfield] - 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_event.UserEvent( - event_type="event_type_value", - visitor_id="visitor_id_value", - session_id="session_id_value", - experiment_ids=["experiment_ids_value"], - attribution_token="attribution_token_value", - cart_id="cart_id_value", - search_query="search_query_value", - filter="filter_value", - order_by="order_by_value", - offset=647, - page_categories=["page_categories_value"], - uri="uri_value", - referrer_uri="referrer_uri_value", - page_view_id="page_view_id_value", - entity="entity_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == "event_type_value" - assert response.visitor_id == "visitor_id_value" - assert response.session_id == "session_id_value" - assert response.experiment_ids == ["experiment_ids_value"] - assert response.attribution_token == "attribution_token_value" - assert response.cart_id == "cart_id_value" - assert response.search_query == "search_query_value" - assert response.filter == "filter_value" - assert response.order_by == "order_by_value" - assert response.offset == 647 - assert response.page_categories == ["page_categories_value"] - assert response.uri == "uri_value" - assert response.referrer_uri == "referrer_uri_value" - assert response.page_view_id == "page_view_id_value" - assert response.entity == "entity_value" - - -def test_write_user_event_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.write_user_event in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.write_user_event - ] = mock_rpc - - request = {} - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.write_user_event(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_write_user_event_rest_required_fields( - request_type=user_event_service.WriteUserEventRequest, -): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" + request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3451,131 +2935,6 @@ def test_write_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_write_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb( - user_event_service.WriteUserEventRequest() - ) - 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_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.WriteUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.CollectUserEventRequest, - dict, - ], -) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( - content_type="content_type_value", - data=b"data_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == "content_type_value" - assert response.data == b"data_blob" - - def test_collect_user_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3736,138 +3095,18 @@ def test_collect_user_event_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_collect_user_event" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb( - user_event_service.CollectUserEventRequest() +def test_purge_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request( - transport: str = "rest", request_type=user_event_service.CollectUserEventRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - purge_config.PurgeUserEventsRequest, - dict, - ], -) -def test_purge_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.purge_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.purge_user_events in client._transport._wrapped_methods @@ -3991,130 +3230,6 @@ def test_purge_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_purge_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_purge_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeUserEventsRequest.pb( - purge_config.PurgeUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = purge_config.PurgeUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_user_events_rest_bad_request( - transport: str = "rest", request_type=purge_config.PurgeUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.purge_user_events(request) - - -def test_purge_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - import_config.ImportUserEventsRequest, - dict, - ], -) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_import_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4248,146 +3363,22 @@ def test_import_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_import_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_import_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb( - import_config.ImportUserEventsRequest() +def test_export_user_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = import_config.ImportUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request( - transport: str = "rest", request_type=import_config.ImportUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - export_config.ExportUserEventsRequest, - dict, - ], -) -def test_export_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.export_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_user_events_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.export_user_events in client._transport._wrapped_methods + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.export_user_events in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -4505,130 +3496,6 @@ def test_export_user_events_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_export_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_export_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = export_config.ExportUserEventsRequest.pb( - export_config.ExportUserEventsRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = export_config.ExportUserEventsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_user_events( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_user_events_rest_bad_request( - transport: str = "rest", request_type=export_config.ExportUserEventsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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.export_user_events(request) - - -def test_export_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - user_event_service.RejoinUserEventsRequest, - dict, - ], -) -def test_rejoin_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.rejoin_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_rejoin_user_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4754,46 +3621,1346 @@ def test_rejoin_user_events_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("parent",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rejoin_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.UserEventServiceRestInterceptor(), ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" - ) as post, mock.patch.object( - transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.RejoinUserEventsRequest.pb( - user_event_service.RejoinUserEventsRequest() + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) - request = user_event_service.RejoinUserEventsRequest() + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +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_transport_kind_grpc(): + transport = UserEventServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserEventServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_write_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + ) + await client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_collect_user_event_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + ) + await client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_purge_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_rejoin_user_events_empty_call_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.rejoin_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserEventServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_write_user_event_rest_bad_request( + request_type=user_event_service.WriteUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.write_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.WriteUserEventRequest, + dict, + ], +) +def test_write_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + request_init["user_event"] = { + "event_type": "event_type_value", + "visitor_id": "visitor_id_value", + "session_id": "session_id_value", + "event_time": {"seconds": 751, "nanos": 543}, + "experiment_ids": ["experiment_ids_value1", "experiment_ids_value2"], + "attribution_token": "attribution_token_value", + "product_details": [ + { + "product": { + "expire_time": {}, + "ttl": {"seconds": 751, "nanos": 543}, + "name": "name_value", + "id": "id_value", + "type_": 1, + "primary_product_id": "primary_product_id_value", + "collection_member_ids": [ + "collection_member_ids_value1", + "collection_member_ids_value2", + ], + "gtin": "gtin_value", + "categories": ["categories_value1", "categories_value2"], + "title": "title_value", + "brands": ["brands_value1", "brands_value2"], + "description": "description_value", + "language_code": "language_code_value", + "attributes": {}, + "tags": ["tags_value1", "tags_value2"], + "price_info": { + "currency_code": "currency_code_value", + "price": 0.531, + "original_price": 0.1479, + "cost": 0.441, + "price_effective_time": {}, + "price_expire_time": {}, + "price_range": { + "price": { + "minimum": 0.764, + "exclusive_minimum": 0.18430000000000002, + "maximum": 0.766, + "exclusive_maximum": 0.1845, + }, + "original_price": {}, + }, + }, + "rating": { + "rating_count": 1293, + "average_rating": 0.1471, + "rating_histogram": [1715, 1716], + }, + "available_time": {}, + "availability": 1, + "available_quantity": {"value": 541}, + "fulfillment_info": [ + { + "type_": "type__value", + "place_ids": ["place_ids_value1", "place_ids_value2"], + } + ], + "uri": "uri_value", + "images": [{"uri": "uri_value", "height": 633, "width": 544}], + "audience": { + "genders": ["genders_value1", "genders_value2"], + "age_groups": ["age_groups_value1", "age_groups_value2"], + }, + "color_info": { + "color_families": [ + "color_families_value1", + "color_families_value2", + ], + "colors": ["colors_value1", "colors_value2"], + }, + "sizes": ["sizes_value1", "sizes_value2"], + "materials": ["materials_value1", "materials_value2"], + "patterns": ["patterns_value1", "patterns_value2"], + "conditions": ["conditions_value1", "conditions_value2"], + "promotions": [{"promotion_id": "promotion_id_value"}], + "publish_time": {}, + "retrievable_fields": {"paths": ["paths_value1", "paths_value2"]}, + "variants": {}, + "local_inventories": [ + { + "place_id": "place_id_value", + "price_info": {}, + "attributes": {}, + "fulfillment_types": [ + "fulfillment_types_value1", + "fulfillment_types_value2", + ], + } + ], + }, + "quantity": {}, + } + ], + "completion_detail": { + "completion_attribution_token": "completion_attribution_token_value", + "selected_suggestion": "selected_suggestion_value", + "selected_position": 1821, + }, + "attributes": {}, + "cart_id": "cart_id_value", + "purchase_transaction": { + "id": "id_value", + "revenue": 0.762, + "tax": 0.333, + "cost": 0.441, + "currency_code": "currency_code_value", + }, + "search_query": "search_query_value", + "filter": "filter_value", + "order_by": "order_by_value", + "offset": 647, + "page_categories": ["page_categories_value1", "page_categories_value2"], + "user_info": { + "user_id": "user_id_value", + "ip_address": "ip_address_value", + "user_agent": "user_agent_value", + "direct_user_request": True, + }, + "uri": "uri_value", + "referrer_uri": "referrer_uri_value", + "page_view_id": "page_view_id_value", + "entity": "entity_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["user_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["user_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][field][subfield] + 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_event.UserEvent( + event_type="event_type_value", + visitor_id="visitor_id_value", + session_id="session_id_value", + experiment_ids=["experiment_ids_value"], + attribution_token="attribution_token_value", + cart_id="cart_id_value", + search_query="search_query_value", + filter="filter_value", + order_by="order_by_value", + offset=647, + page_categories=["page_categories_value"], + uri="uri_value", + referrer_uri="referrer_uri_value", + page_view_id="page_view_id_value", + entity="entity_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == "event_type_value" + assert response.visitor_id == "visitor_id_value" + assert response.session_id == "session_id_value" + assert response.experiment_ids == ["experiment_ids_value"] + assert response.attribution_token == "attribution_token_value" + assert response.cart_id == "cart_id_value" + assert response.search_query == "search_query_value" + assert response.filter == "filter_value" + assert response.order_by == "order_by_value" + assert response.offset == 647 + assert response.page_categories == ["page_categories_value"] + assert response.uri == "uri_value" + assert response.referrer_uri == "referrer_uri_value" + assert response.page_view_id == "page_view_id_value" + assert response.entity == "entity_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_write_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_write_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb( + user_event_service.WriteUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = user_event.UserEvent.to_json(user_event.UserEvent()) + req.return_value.content = return_value + + request = user_event_service.WriteUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request( + request_type=user_event_service.CollectUserEventRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.collect_user_event(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.CollectUserEventRequest, + dict, + ], +) +def test_collect_user_event_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = httpbody_pb2.HttpBody( + content_type="content_type_value", + data=b"data_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == "content_type_value" + assert response.data == b"data_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_collect_user_event" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_collect_user_event" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb( + user_event_service.CollectUserEventRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(httpbody_pb2.HttpBody()) + req.return_value.content = return_value + + request = user_event_service.CollectUserEventRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request( + request_type=purge_config.PurgeUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.purge_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeUserEventsRequest, + dict, + ], +) +def test_purge_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_purge_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_purge_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeUserEventsRequest.pb( + purge_config.PurgeUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = purge_config.PurgeUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request( + request_type=import_config.ImportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportUserEventsRequest, + dict, + ], +) +def test_import_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_import_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_import_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb( + import_config.ImportUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = import_config.ImportUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_user_events_rest_bad_request( + request_type=export_config.ExportUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.export_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + export_config.ExportUserEventsRequest, + dict, + ], +) +def test_export_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.export_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_export_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_export_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = export_config.ExportUserEventsRequest.pb( + export_config.ExportUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = export_config.ExportUserEventsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_user_events( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rejoin_user_events_rest_bad_request( + request_type=user_event_service.RejoinUserEventsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.rejoin_user_events(request) + + +@pytest.mark.parametrize( + "request_type", + [ + user_event_service.RejoinUserEventsRequest, + dict, + ], +) +def test_rejoin_user_events_rest_call_success(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.rejoin_user_events(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rejoin_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.UserEventServiceRestInterceptor, "post_rejoin_user_events" + ) as post, mock.patch.object( + transports.UserEventServiceRestInterceptor, "pre_rejoin_user_events" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.RejoinUserEventsRequest.pb( + user_event_service.RejoinUserEventsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = user_event_service.RejoinUserEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -4813,17 +4980,82 @@ def test_rejoin_user_events_rest_interceptors(null_interceptor): post.assert_called_once() -def test_rejoin_user_events_rest_bad_request( - transport: str = "rest", request_type=user_event_service.RejoinUserEventsRequest +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, ): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + }, + request, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/catalogs/sample3"} + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" + } request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( @@ -4831,122 +5063,200 @@ def test_rejoin_user_events_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.rejoin_user_events(request) + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/catalogs/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_rejoin_user_events_rest_error(): + +def test_initialize_client_w_rest(): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + assert client is not None -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_write_user_event_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.write_user_event), "__call__") as call: + client.write_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.WriteUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_collect_user_event_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), "__call__" + ) as call: + client.collect_user_event(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.CollectUserEventRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_purge_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), "__call__" + ) as call: + client.purge_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = purge_config.PurgeUserEventsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_user_events_empty_call_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), "__call__" + ) as call: + client.import_user_events(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = import_config.ImportUserEventsRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + assert args[0] == request_msg -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_user_events), "__call__" + ) as call: + client.export_user_events(request=None) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = export_config.ExportUserEventsRequest() - transport = transports.UserEventServiceGrpcAsyncIOTransport( + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_rejoin_user_events_empty_call_rest(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.rejoin_user_events), "__call__" + ) as call: + client.rejoin_user_events(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user_event_service.RejoinUserEventsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -5190,23 +5500,6 @@ def test_user_event_service_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -5636,141 +5929,6 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - }, - request, - ) - - # 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_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = { - "name": "projects/sample1/locations/sample2/catalogs/sample3/branches/sample4/operations/sample5" - } - 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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/catalogs/sample3"}, request - ) - - # 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.list_operations(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/catalogs/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 = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - def test_get_operation(transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5798,7 +5956,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5853,7 +6011,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5900,7 +6058,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5943,7 +6101,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5998,7 +6156,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -6045,7 +6203,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -6061,22 +6219,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = UserEventServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/google/cloud/run/gapic_version.py b/packages/google-cloud-run/google/cloud/run/gapic_version.py index 1ade039fad47..558c8aab67c5 100644 --- a/packages/google-cloud-run/google/cloud/run/gapic_version.py +++ b/packages/google-cloud-run/google/cloud/run/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.9" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py b/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py index 1ade039fad47..558c8aab67c5 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py +++ b/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.9" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/async_client.py index db45db73e87f..b8aad7365599 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/async_client.py @@ -367,11 +367,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -424,11 +420,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -485,11 +477,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -545,11 +533,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/client.py index e7fdd36add08..31a42d52428d 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/client.py @@ -808,11 +808,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -865,11 +861,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -926,11 +918,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -986,11 +974,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/README.rst new file mode 100644 index 000000000000..eb8929cb53d9 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BuildsTransport` is the ABC for all transports. +- public child `BuildsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BuildsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBuildsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BuildsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/base.py index c30ed50a208d..b335c8b1baf6 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/base.py @@ -135,6 +135,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc.py index 3097fbc74d50..80dd8298cff3 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc.py @@ -291,7 +291,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc_asyncio.py index d4277b75fc04..8641cc12b296 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -269,16 +273,45 @@ def submit_build( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.submit_build: gapic_v1.method_async.wrap_method( + self.submit_build: self._wrap_method( self.submit_build, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -305,7 +338,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest.py index 7e8ec2f6ff01..e8a435ca9a28 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.run_v2.types import build + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBuildsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.run_v2.types import build - -from .base import BuildsTransport -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, @@ -199,8 +195,8 @@ class BuildsRestStub: _interceptor: BuildsRestInterceptor -class BuildsRestTransport(BuildsTransport): - """REST backend transport for Builds. +class BuildsRestTransport(_BaseBuildsRestTransport): + """REST backend synchronous transport for Builds. Cloud Run Build Control Plane API @@ -209,7 +205,6 @@ class BuildsRestTransport(BuildsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -263,21 +258,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -288,19 +274,32 @@ def __init__( self._interceptor = interceptor or BuildsRestInterceptor() self._prep_wrapped_messages(client_info) - class _SubmitBuild(BuildsRestStub): + class _SubmitBuild(_BaseBuildsRestTransport._BaseSubmitBuild, BuildsRestStub): def __hash__(self): - return hash("SubmitBuild") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("BuildsRestTransport.SubmitBuild") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -329,45 +328,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*}/builds:submit", - "body": "*", - }, - ] + http_options = _BaseBuildsRestTransport._BaseSubmitBuild._get_http_options() request, metadata = self._interceptor.pre_submit_build(request, metadata) - pb_request = build.SubmitBuildRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseBuildsRestTransport._BaseSubmitBuild._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseBuildsRestTransport._BaseSubmitBuild._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseBuildsRestTransport._BaseSubmitBuild._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = BuildsRestTransport._SubmitBuild._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -395,7 +383,34 @@ def submit_build( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(BuildsRestStub): + class _DeleteOperation( + _BaseBuildsRestTransport._BaseDeleteOperation, BuildsRestStub + ): + def __hash__(self): + return hash("BuildsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -416,34 +431,33 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseBuildsRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseBuildsRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseBuildsRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = BuildsRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -457,7 +471,32 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(BuildsRestStub): + class _GetOperation(_BaseBuildsRestTransport._BaseGetOperation, BuildsRestStub): + def __hash__(self): + return hash("BuildsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -481,32 +520,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseBuildsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseBuildsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseBuildsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = BuildsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -514,8 +552,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -523,7 +562,32 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(BuildsRestStub): + class _ListOperations(_BaseBuildsRestTransport._BaseListOperations, BuildsRestStub): + def __hash__(self): + return hash("BuildsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -547,32 +611,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseBuildsRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseBuildsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseBuildsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = BuildsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -580,8 +643,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -589,7 +653,33 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(BuildsRestStub): + class _WaitOperation(_BaseBuildsRestTransport._BaseWaitOperation, BuildsRestStub): + def __hash__(self): + return hash("BuildsRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -613,35 +703,36 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = ( + _BaseBuildsRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseBuildsRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseBuildsRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseBuildsRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = BuildsRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -649,8 +740,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest_base.py new file mode 100644 index 000000000000..25472f5d5db7 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/builds/transports/rest_base.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import build + +from .base import DEFAULT_CLIENT_INFO, BuildsTransport + + +class _BaseBuildsRestTransport(BuildsTransport): + """Base REST backend transport for Builds. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseSubmitBuild: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/builds:submit", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = build.SubmitBuildRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBuildsRestTransport._BaseSubmitBuild._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseBuildsRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/async_client.py index 44bc25179902..fe756fc51179 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/async_client.py @@ -775,11 +775,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -832,11 +828,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -893,11 +885,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -953,11 +941,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/client.py index a714f76bdc8d..94d1b1e15c44 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/client.py @@ -1299,11 +1299,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1356,11 +1352,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1417,11 +1409,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1477,11 +1465,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/README.rst new file mode 100644 index 000000000000..6555db202c9c --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ExecutionsTransport` is the ABC for all transports. +- public child `ExecutionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ExecutionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseExecutionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ExecutionsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/base.py index 9ea2ecaf2cc5..1af98b7b367e 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/base.py @@ -150,6 +150,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc.py index df33f44870fc..d0492b5a4129 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc.py @@ -385,7 +385,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc_asyncio.py index 2603f5db08f2..df1b30c72680 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -371,31 +375,60 @@ def cancel_execution( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_execution: gapic_v1.method_async.wrap_method( + self.get_execution: self._wrap_method( self.get_execution, default_timeout=None, client_info=client_info, ), - self.list_executions: gapic_v1.method_async.wrap_method( + self.list_executions: self._wrap_method( self.list_executions, default_timeout=None, client_info=client_info, ), - self.delete_execution: gapic_v1.method_async.wrap_method( + self.delete_execution: self._wrap_method( self.delete_execution, default_timeout=None, client_info=client_info, ), - self.cancel_execution: gapic_v1.method_async.wrap_method( + self.cancel_execution: self._wrap_method( self.cancel_execution, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -422,7 +455,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest.py index 302f94e9503c..f57266b521d7 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.run_v2.types import execution + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseExecutionsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.run_v2.types import execution - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ExecutionsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -298,8 +288,8 @@ class ExecutionsRestStub: _interceptor: ExecutionsRestInterceptor -class ExecutionsRestTransport(ExecutionsTransport): - """REST backend transport for Executions. +class ExecutionsRestTransport(_BaseExecutionsRestTransport): + """REST backend synchronous transport for Executions. Cloud Run Execution Control Plane API. @@ -308,7 +298,6 @@ class ExecutionsRestTransport(ExecutionsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -362,21 +351,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -441,19 +421,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CancelExecution(ExecutionsRestStub): + class _CancelExecution( + _BaseExecutionsRestTransport._BaseCancelExecution, ExecutionsRestStub + ): def __hash__(self): - return hash("CancelExecution") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ExecutionsRestTransport.CancelExecution") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -483,47 +478,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}:cancel", - "body": "*", - }, - ] + http_options = ( + _BaseExecutionsRestTransport._BaseCancelExecution._get_http_options() + ) request, metadata = self._interceptor.pre_cancel_execution( request, metadata ) - pb_request = execution.CancelExecutionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseExecutionsRestTransport._BaseCancelExecution._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseExecutionsRestTransport._BaseCancelExecution._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseExecutionsRestTransport._BaseCancelExecution._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ExecutionsRestTransport._CancelExecution._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -537,19 +519,33 @@ def __call__( resp = self._interceptor.post_cancel_execution(resp) return resp - class _DeleteExecution(ExecutionsRestStub): + class _DeleteExecution( + _BaseExecutionsRestTransport._BaseDeleteExecution, ExecutionsRestStub + ): def __hash__(self): - return hash("DeleteExecution") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ExecutionsRestTransport.DeleteExecution") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -579,40 +575,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}", - }, - ] + http_options = ( + _BaseExecutionsRestTransport._BaseDeleteExecution._get_http_options() + ) request, metadata = self._interceptor.pre_delete_execution( request, metadata ) - pb_request = execution.DeleteExecutionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseExecutionsRestTransport._BaseDeleteExecution._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseExecutionsRestTransport._BaseDeleteExecution._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ExecutionsRestTransport._DeleteExecution._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -626,19 +611,33 @@ def __call__( resp = self._interceptor.post_delete_execution(resp) return resp - class _GetExecution(ExecutionsRestStub): + class _GetExecution( + _BaseExecutionsRestTransport._BaseGetExecution, ExecutionsRestStub + ): def __hash__(self): - return hash("GetExecution") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ExecutionsRestTransport.GetExecution") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -670,38 +669,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}", - }, - ] + http_options = ( + _BaseExecutionsRestTransport._BaseGetExecution._get_http_options() + ) request, metadata = self._interceptor.pre_get_execution(request, metadata) - pb_request = execution.GetExecutionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseExecutionsRestTransport._BaseGetExecution._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseExecutionsRestTransport._BaseGetExecution._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ExecutionsRestTransport._GetExecution._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -717,19 +709,33 @@ def __call__( resp = self._interceptor.post_get_execution(resp) return resp - class _ListExecutions(ExecutionsRestStub): + class _ListExecutions( + _BaseExecutionsRestTransport._BaseListExecutions, ExecutionsRestStub + ): def __hash__(self): - return hash("ListExecutions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ExecutionsRestTransport.ListExecutions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -758,38 +764,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/jobs/*}/executions", - }, - ] + http_options = ( + _BaseExecutionsRestTransport._BaseListExecutions._get_http_options() + ) request, metadata = self._interceptor.pre_list_executions(request, metadata) - pb_request = execution.ListExecutionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseExecutionsRestTransport._BaseListExecutions._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseExecutionsRestTransport._BaseListExecutions._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ExecutionsRestTransport._ListExecutions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -841,7 +838,34 @@ def list_executions( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(ExecutionsRestStub): + class _DeleteOperation( + _BaseExecutionsRestTransport._BaseDeleteOperation, ExecutionsRestStub + ): + def __hash__(self): + return hash("ExecutionsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -862,34 +886,29 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseExecutionsRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseExecutionsRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = _BaseExecutionsRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) # 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), + response = ExecutionsRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -903,7 +922,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ExecutionsRestStub): + class _GetOperation( + _BaseExecutionsRestTransport._BaseGetOperation, ExecutionsRestStub + ): + def __hash__(self): + return hash("ExecutionsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -927,32 +973,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseExecutionsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseExecutionsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseExecutionsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ExecutionsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -960,8 +1005,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -969,7 +1015,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ExecutionsRestStub): + class _ListOperations( + _BaseExecutionsRestTransport._BaseListOperations, ExecutionsRestStub + ): + def __hash__(self): + return hash("ExecutionsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -993,32 +1066,29 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseExecutionsRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseExecutionsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseExecutionsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ExecutionsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1026,8 +1096,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -1035,7 +1106,35 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(ExecutionsRestStub): + class _WaitOperation( + _BaseExecutionsRestTransport._BaseWaitOperation, ExecutionsRestStub + ): + def __hash__(self): + return hash("ExecutionsRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -1059,35 +1158,38 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = ( + _BaseExecutionsRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseExecutionsRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = ( + _BaseExecutionsRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseExecutionsRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = ExecutionsRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1095,8 +1197,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest_base.py new file mode 100644 index 000000000000..ae663a508fc6 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/executions/transports/rest_base.py @@ -0,0 +1,397 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import execution + +from .base import DEFAULT_CLIENT_INFO, ExecutionsTransport + + +class _BaseExecutionsRestTransport(ExecutionsTransport): + """Base REST backend transport for Executions. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCancelExecution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = execution.CancelExecutionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExecutionsRestTransport._BaseCancelExecution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteExecution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = execution.DeleteExecutionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExecutionsRestTransport._BaseDeleteExecution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetExecution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = execution.GetExecutionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExecutionsRestTransport._BaseGetExecution._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListExecutions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/jobs/*}/executions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = execution.ListExecutionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseExecutionsRestTransport._BaseListExecutions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseExecutionsRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/async_client.py index b41ee497e867..babaec5a8ff1 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/async_client.py @@ -387,11 +387,19 @@ async def sample_create_job(): self._client._transport.create_job ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -503,11 +511,19 @@ async def sample_get_job(): # and friendly error handling. rpc = self._client._transport._wrapped_methods[self._client._transport.get_job] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -617,11 +633,19 @@ async def sample_list_jobs(): self._client._transport.list_jobs ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -741,11 +765,19 @@ async def sample_update_job(): self._client._transport.update_job ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("job.name", request.job.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.job.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -864,11 +896,19 @@ async def sample_delete_job(): self._client._transport.delete_job ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -986,11 +1026,19 @@ async def sample_run_job(): # and friendly error handling. rpc = self._client._transport._wrapped_methods[self._client._transport.run_job] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -1364,11 +1412,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1421,11 +1465,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1482,11 +1522,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1542,11 +1578,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/client.py index 19f51f6caf36..99af137f6e8b 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/client.py @@ -1946,11 +1946,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -2003,11 +1999,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2064,11 +2056,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2124,11 +2112,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/README.rst new file mode 100644 index 000000000000..098a69237e16 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`JobsTransport` is the ABC for all transports. +- public child `JobsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `JobsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseJobsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `JobsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/base.py index 1751f2417992..c8e9097f759a 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/base.py @@ -178,6 +178,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc.py index a58f18a1c925..9493b0cc95fa 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc.py @@ -519,7 +519,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc_asyncio.py index 25eb431e2d1a..219ca188ebdf 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -505,56 +509,85 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_job: gapic_v1.method_async.wrap_method( + self.create_job: self._wrap_method( self.create_job, default_timeout=None, client_info=client_info, ), - self.get_job: gapic_v1.method_async.wrap_method( + self.get_job: self._wrap_method( self.get_job, default_timeout=None, client_info=client_info, ), - self.list_jobs: gapic_v1.method_async.wrap_method( + self.list_jobs: self._wrap_method( self.list_jobs, default_timeout=None, client_info=client_info, ), - self.update_job: gapic_v1.method_async.wrap_method( + self.update_job: self._wrap_method( self.update_job, default_timeout=None, client_info=client_info, ), - self.delete_job: gapic_v1.method_async.wrap_method( + self.delete_job: self._wrap_method( self.delete_job, default_timeout=None, client_info=client_info, ), - self.run_job: gapic_v1.method_async.wrap_method( + self.run_job: self._wrap_method( self.run_job, default_timeout=None, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_timeout=None, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=None, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -581,7 +614,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest.py index be14acdddf10..69e4be494c44 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.run_v2.types import job from google.cloud.run_v2.types import job as gcr_job from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import JobsTransport +from .rest_base import _BaseJobsRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -438,8 +428,8 @@ class JobsRestStub: _interceptor: JobsRestInterceptor -class JobsRestTransport(JobsTransport): - """REST backend transport for Jobs. +class JobsRestTransport(_BaseJobsRestTransport): + """REST backend synchronous transport for Jobs. Cloud Run Job Control Plane API. @@ -448,7 +438,6 @@ class JobsRestTransport(JobsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -502,21 +491,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -581,21 +561,32 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateJob(JobsRestStub): + class _CreateJob(_BaseJobsRestTransport._BaseCreateJob, JobsRestStub): def __hash__(self): - return hash("CreateJob") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "jobId": "", - } - - @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 - } + return hash("JobsRestTransport.CreateJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -624,45 +615,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*}/jobs", - "body": "job", - }, - ] + http_options = _BaseJobsRestTransport._BaseCreateJob._get_http_options() request, metadata = self._interceptor.pre_create_job(request, metadata) - pb_request = gcr_job.CreateJobRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseJobsRestTransport._BaseCreateJob._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseJobsRestTransport._BaseCreateJob._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseJobsRestTransport._BaseCreateJob._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = JobsRestTransport._CreateJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -676,19 +654,31 @@ def __call__( resp = self._interceptor.post_create_job(resp) return resp - class _DeleteJob(JobsRestStub): + class _DeleteJob(_BaseJobsRestTransport._BaseDeleteJob, JobsRestStub): def __hash__(self): - return hash("DeleteJob") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.DeleteJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -718,38 +708,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/jobs/*}", - }, - ] + http_options = _BaseJobsRestTransport._BaseDeleteJob._get_http_options() request, metadata = self._interceptor.pre_delete_job(request, metadata) - pb_request = job.DeleteJobRequest.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"], - use_integers_for_enums=True, + transcoded_request = ( + _BaseJobsRestTransport._BaseDeleteJob._get_transcoded_request( + http_options, request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + # Jsonify the query params + query_params = _BaseJobsRestTransport._BaseDeleteJob._get_query_params_json( + transcoded_request + ) # 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), + response = JobsRestTransport._DeleteJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -763,19 +742,31 @@ def __call__( resp = self._interceptor.post_delete_job(resp) return resp - class _GetIamPolicy(JobsRestStub): + class _GetIamPolicy(_BaseJobsRestTransport._BaseGetIamPolicy, JobsRestStub): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -876,38 +867,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:getIamPolicy", - }, - ] + http_options = _BaseJobsRestTransport._BaseGetIamPolicy._get_http_options() request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseJobsRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseJobsRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = JobsRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -923,19 +905,31 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetJob(JobsRestStub): + class _GetJob(_BaseJobsRestTransport._BaseGetJob, JobsRestStub): def __hash__(self): - return hash("GetJob") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.GetJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -965,38 +959,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/jobs/*}", - }, - ] + http_options = _BaseJobsRestTransport._BaseGetJob._get_http_options() request, metadata = self._interceptor.pre_get_job(request, metadata) - pb_request = job.GetJobRequest.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"], - use_integers_for_enums=True, + transcoded_request = ( + _BaseJobsRestTransport._BaseGetJob._get_transcoded_request( + http_options, request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + # Jsonify the query params + query_params = _BaseJobsRestTransport._BaseGetJob._get_query_params_json( + transcoded_request + ) # 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), + response = JobsRestTransport._GetJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1012,19 +995,31 @@ def __call__( resp = self._interceptor.post_get_job(resp) return resp - class _ListJobs(JobsRestStub): + class _ListJobs(_BaseJobsRestTransport._BaseListJobs, JobsRestStub): def __hash__(self): - return hash("ListJobs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.ListJobs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1053,38 +1048,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*}/jobs", - }, - ] + http_options = _BaseJobsRestTransport._BaseListJobs._get_http_options() request, metadata = self._interceptor.pre_list_jobs(request, metadata) - pb_request = job.ListJobsRequest.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"], - use_integers_for_enums=True, + transcoded_request = ( + _BaseJobsRestTransport._BaseListJobs._get_transcoded_request( + http_options, request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + # Jsonify the query params + query_params = _BaseJobsRestTransport._BaseListJobs._get_query_params_json( + transcoded_request + ) # 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), + response = JobsRestTransport._ListJobs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1100,19 +1084,32 @@ def __call__( resp = self._interceptor.post_list_jobs(resp) return resp - class _RunJob(JobsRestStub): + class _RunJob(_BaseJobsRestTransport._BaseRunJob, JobsRestStub): def __hash__(self): - return hash("RunJob") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.RunJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1142,45 +1139,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/jobs/*}:run", - "body": "*", - }, - ] + http_options = _BaseJobsRestTransport._BaseRunJob._get_http_options() request, metadata = self._interceptor.pre_run_job(request, metadata) - pb_request = job.RunJobRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseJobsRestTransport._BaseRunJob._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseJobsRestTransport._BaseRunJob._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseJobsRestTransport._BaseRunJob._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = JobsRestTransport._RunJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1194,19 +1178,32 @@ def __call__( resp = self._interceptor.post_run_job(resp) return resp - class _SetIamPolicy(JobsRestStub): + class _SetIamPolicy(_BaseJobsRestTransport._BaseSetIamPolicy, JobsRestStub): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1307,45 +1304,34 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = _BaseJobsRestTransport._BaseSetIamPolicy._get_http_options() request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseJobsRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseJobsRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseJobsRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = JobsRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1361,19 +1347,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(JobsRestStub): + class _TestIamPermissions( + _BaseJobsRestTransport._BaseTestIamPermissions, JobsRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1399,47 +1400,40 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseJobsRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseJobsRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = ( + _BaseJobsRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseJobsRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = JobsRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1455,19 +1449,32 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UpdateJob(JobsRestStub): + class _UpdateJob(_BaseJobsRestTransport._BaseUpdateJob, JobsRestStub): def __hash__(self): - return hash("UpdateJob") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("JobsRestTransport.UpdateJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1496,45 +1503,32 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{job.name=projects/*/locations/*/jobs/*}", - "body": "job", - }, - ] + http_options = _BaseJobsRestTransport._BaseUpdateJob._get_http_options() request, metadata = self._interceptor.pre_update_job(request, metadata) - pb_request = gcr_job.UpdateJobRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseJobsRestTransport._BaseUpdateJob._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseJobsRestTransport._BaseUpdateJob._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseJobsRestTransport._BaseUpdateJob._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = JobsRestTransport._UpdateJob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1619,7 +1613,32 @@ def update_job( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(JobsRestStub): + class _DeleteOperation(_BaseJobsRestTransport._BaseDeleteOperation, JobsRestStub): + def __hash__(self): + return hash("JobsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1640,34 +1659,33 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseJobsRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseJobsRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseJobsRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = JobsRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1681,7 +1699,32 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(JobsRestStub): + class _GetOperation(_BaseJobsRestTransport._BaseGetOperation, JobsRestStub): + def __hash__(self): + return hash("JobsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1705,32 +1748,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = _BaseJobsRestTransport._BaseGetOperation._get_http_options() request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseJobsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseJobsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = JobsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1738,8 +1778,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1747,7 +1788,32 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(JobsRestStub): + class _ListOperations(_BaseJobsRestTransport._BaseListOperations, JobsRestStub): + def __hash__(self): + return hash("JobsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1771,32 +1837,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseJobsRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseJobsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseJobsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = JobsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1804,8 +1869,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -1813,7 +1879,33 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(JobsRestStub): + class _WaitOperation(_BaseJobsRestTransport._BaseWaitOperation, JobsRestStub): + def __hash__(self): + return hash("JobsRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -1837,35 +1929,34 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = _BaseJobsRestTransport._BaseWaitOperation._get_http_options() request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseJobsRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseJobsRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseJobsRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = JobsRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1873,8 +1964,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest_base.py new file mode 100644 index 000000000000..298da4c0113a --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/jobs/transports/rest_base.py @@ -0,0 +1,677 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import job +from google.cloud.run_v2.types import job as gcr_job + +from .base import DEFAULT_CLIENT_INFO, JobsTransport + + +class _BaseJobsRestTransport(JobsTransport): + """Base REST backend transport for Jobs. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "jobId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/jobs", + "body": "job", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcr_job.CreateJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseCreateJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/jobs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = job.DeleteJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseDeleteJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/jobs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = job.GetJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseGetJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListJobs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/jobs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = job.ListJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseListJobs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRunJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/jobs/*}:run", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = job.RunJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseRunJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/jobs/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{job.name=projects/*/locations/*/jobs/*}", + "body": "job", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcr_job.UpdateJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseJobsRestTransport._BaseUpdateJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseJobsRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py index 37ff9b05024c..e5917935da4d 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py @@ -365,11 +365,19 @@ async def sample_get_revision(): self._client._transport.get_revision ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -481,11 +489,19 @@ async def sample_list_revisions(): self._client._transport.list_revisions ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -610,11 +626,19 @@ async def sample_delete_revision(): self._client._transport.delete_revision ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -669,11 +693,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -726,11 +746,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -787,11 +803,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -847,11 +859,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py index 05953885ca89..1defa93d4f09 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py @@ -1240,11 +1240,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1297,11 +1293,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1358,11 +1350,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1418,11 +1406,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/README.rst new file mode 100644 index 000000000000..81dc915c3637 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RevisionsTransport` is the ABC for all transports. +- public child `RevisionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RevisionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRevisionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RevisionsRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/base.py index fb963e1216da..96ee32d9448b 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/base.py @@ -145,6 +145,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc.py index 8c367dbb1a12..53051de73f83 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc.py @@ -360,7 +360,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py index 0f0c9fcdb39d..374c7fd2f355 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -229,6 +230,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -344,26 +348,55 @@ def delete_revision( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_revision: gapic_v1.method_async.wrap_method( + self.get_revision: self._wrap_method( self.get_revision, default_timeout=None, client_info=client_info, ), - self.list_revisions: gapic_v1.method_async.wrap_method( + self.list_revisions: self._wrap_method( self.list_revisions, default_timeout=None, client_info=client_info, ), - self.delete_revision: gapic_v1.method_async.wrap_method( + self.delete_revision: self._wrap_method( self.delete_revision, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -390,7 +423,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest.py index 34f40c6bbce0..4f9cbb9ec6bc 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest.py @@ -16,40 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.run_v2.types import revision + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRevisionsRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.run_v2.types import revision - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import RevisionsTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -265,8 +255,8 @@ class RevisionsRestStub: _interceptor: RevisionsRestInterceptor -class RevisionsRestTransport(RevisionsTransport): - """REST backend transport for Revisions. +class RevisionsRestTransport(_BaseRevisionsRestTransport): + """REST backend synchronous transport for Revisions. Cloud Run Revision Control Plane API. @@ -275,7 +265,6 @@ class RevisionsRestTransport(RevisionsTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -329,21 +318,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -408,19 +388,33 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _DeleteRevision(RevisionsRestStub): + class _DeleteRevision( + _BaseRevisionsRestTransport._BaseDeleteRevision, RevisionsRestStub + ): def __hash__(self): - return hash("DeleteRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RevisionsRestTransport.DeleteRevision") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -453,38 +447,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", - }, - ] + http_options = ( + _BaseRevisionsRestTransport._BaseDeleteRevision._get_http_options() + ) request, metadata = self._interceptor.pre_delete_revision(request, metadata) - pb_request = revision.DeleteRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRevisionsRestTransport._BaseDeleteRevision._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRevisionsRestTransport._BaseDeleteRevision._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RevisionsRestTransport._DeleteRevision._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -498,19 +485,31 @@ def __call__( resp = self._interceptor.post_delete_revision(resp) return resp - class _GetRevision(RevisionsRestStub): + class _GetRevision(_BaseRevisionsRestTransport._BaseGetRevision, RevisionsRestStub): def __hash__(self): - return hash("GetRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RevisionsRestTransport.GetRevision") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -542,38 +541,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", - }, - ] + http_options = ( + _BaseRevisionsRestTransport._BaseGetRevision._get_http_options() + ) request, metadata = self._interceptor.pre_get_revision(request, metadata) - pb_request = revision.GetRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRevisionsRestTransport._BaseGetRevision._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRevisionsRestTransport._BaseGetRevision._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RevisionsRestTransport._GetRevision._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -589,19 +581,33 @@ def __call__( resp = self._interceptor.post_get_revision(resp) return resp - class _ListRevisions(RevisionsRestStub): + class _ListRevisions( + _BaseRevisionsRestTransport._BaseListRevisions, RevisionsRestStub + ): def __hash__(self): - return hash("ListRevisions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("RevisionsRestTransport.ListRevisions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -630,38 +636,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/services/*}/revisions", - }, - ] + http_options = ( + _BaseRevisionsRestTransport._BaseListRevisions._get_http_options() + ) request, metadata = self._interceptor.pre_list_revisions(request, metadata) - pb_request = revision.ListRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRevisionsRestTransport._BaseListRevisions._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseRevisionsRestTransport._BaseListRevisions._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = RevisionsRestTransport._ListRevisions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -705,7 +704,34 @@ def list_revisions( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(RevisionsRestStub): + class _DeleteOperation( + _BaseRevisionsRestTransport._BaseDeleteOperation, RevisionsRestStub + ): + def __hash__(self): + return hash("RevisionsRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -726,34 +752,31 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseRevisionsRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = _BaseRevisionsRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseRevisionsRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = RevisionsRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -767,7 +790,34 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(RevisionsRestStub): + class _GetOperation( + _BaseRevisionsRestTransport._BaseGetOperation, RevisionsRestStub + ): + def __hash__(self): + return hash("RevisionsRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -791,32 +841,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseRevisionsRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRevisionsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseRevisionsRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = RevisionsRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -824,8 +873,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -833,7 +883,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(RevisionsRestStub): + class _ListOperations( + _BaseRevisionsRestTransport._BaseListOperations, RevisionsRestStub + ): + def __hash__(self): + return hash("RevisionsRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -857,32 +934,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseRevisionsRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseRevisionsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseRevisionsRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = RevisionsRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -890,8 +966,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -899,7 +976,35 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(RevisionsRestStub): + class _WaitOperation( + _BaseRevisionsRestTransport._BaseWaitOperation, RevisionsRestStub + ): + def __hash__(self): + return hash("RevisionsRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -923,35 +1028,38 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = ( + _BaseRevisionsRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseRevisionsRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = ( + _BaseRevisionsRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseRevisionsRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = RevisionsRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -959,8 +1067,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest_base.py new file mode 100644 index 000000000000..3c2095bc0dae --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/transports/rest_base.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import revision + +from .base import DEFAULT_CLIENT_INFO, RevisionsTransport + + +class _BaseRevisionsRestTransport(RevisionsTransport): + """Base REST backend transport for Revisions. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseDeleteRevision: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = revision.DeleteRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRevisionsRestTransport._BaseDeleteRevision._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRevision: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/services/*/revisions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = revision.GetRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRevisionsRestTransport._BaseGetRevision._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRevisions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/services/*}/revisions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = revision.ListRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRevisionsRestTransport._BaseListRevisions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseRevisionsRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/async_client.py index 28d259c68b51..b84c67188765 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/async_client.py @@ -399,11 +399,19 @@ async def sample_create_service(): self._client._transport.create_service ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -523,11 +531,19 @@ async def sample_get_service(): self._client._transport.get_service ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -639,11 +655,19 @@ async def sample_list_services(): self._client._transport.list_services ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -774,13 +798,19 @@ async def sample_update_service(): self._client._transport.update_service ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("service.name", request.service.name),) - ), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.service.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -906,11 +936,19 @@ async def sample_delete_service(): self._client._transport.delete_service ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)(?:/.*)?$" ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) # Validate the universe domain. self._client._validate_universe_domain() @@ -1284,11 +1322,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1341,11 +1375,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1402,11 +1432,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1462,11 +1488,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/client.py index 65ad349bd447..947bbdedbefb 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/client.py @@ -1875,11 +1875,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1932,11 +1928,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1993,11 +1985,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -2053,11 +2041,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/README.rst new file mode 100644 index 000000000000..ac1c48dcd4e6 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ServicesTransport` is the ABC for all transports. +- public child `ServicesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ServicesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseServicesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ServicesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/base.py index aa9c1cec527f..b27d041c938f 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/base.py @@ -191,6 +191,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc.py index 6671d9169e57..9ea21b579f53 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc.py @@ -502,7 +502,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc_asyncio.py index 6ff213309a38..3cfe78a8bcfe 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -232,6 +233,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -490,12 +494,12 @@ def test_iam_permissions( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.create_service: gapic_v1.method_async.wrap_method( + self.create_service: self._wrap_method( self.create_service, default_timeout=15.0, client_info=client_info, ), - self.get_service: gapic_v1.method_async.wrap_method( + self.get_service: self._wrap_method( self.get_service, default_retry=retries.AsyncRetry( initial=1.0, @@ -509,7 +513,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.list_services: gapic_v1.method_async.wrap_method( + self.list_services: self._wrap_method( self.list_services, default_retry=retries.AsyncRetry( initial=1.0, @@ -523,36 +527,65 @@ def _prep_wrapped_messages(self, client_info): default_timeout=10.0, client_info=client_info, ), - self.update_service: gapic_v1.method_async.wrap_method( + self.update_service: self._wrap_method( self.update_service, default_timeout=15.0, client_info=client_info, ), - self.delete_service: gapic_v1.method_async.wrap_method( + self.delete_service: self._wrap_method( self.delete_service, default_timeout=10.0, client_info=client_info, ), - self.get_iam_policy: gapic_v1.method_async.wrap_method( + self.get_iam_policy: self._wrap_method( self.get_iam_policy, default_timeout=None, client_info=client_info, ), - self.set_iam_policy: gapic_v1.method_async.wrap_method( + self.set_iam_policy: self._wrap_method( self.set_iam_policy, default_timeout=None, client_info=client_info, ), - self.test_iam_permissions: gapic_v1.method_async.wrap_method( + self.test_iam_permissions: self._wrap_method( self.test_iam_permissions, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -579,7 +612,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest.py index ba56c5a8d65b..3dfd82951f7e 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest.py @@ -16,42 +16,32 @@ import dataclasses import json # type: ignore -import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings -from google.api_core import ( - gapic_v1, - operations_v1, - path_template, - rest_helpers, - rest_streaming, -) +from google.api_core import gapic_v1, operations_v1, 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.cloud.location import locations_pb2 # 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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version from google.cloud.run_v2.types import service from google.cloud.run_v2.types import service as gcr_service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import ServicesTransport +from .rest_base import _BaseServicesRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -415,8 +405,8 @@ class ServicesRestStub: _interceptor: ServicesRestInterceptor -class ServicesRestTransport(ServicesTransport): - """REST backend transport for Services. +class ServicesRestTransport(_BaseServicesRestTransport): + """REST backend synchronous transport for Services. Cloud Run Service Control Plane API @@ -425,7 +415,6 @@ class ServicesRestTransport(ServicesTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -479,21 +468,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -558,21 +538,34 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateService(ServicesRestStub): + class _CreateService( + _BaseServicesRestTransport._BaseCreateService, ServicesRestStub + ): def __hash__(self): - return hash("CreateService") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "serviceId": "", - } - - @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 - } + return hash("ServicesRestTransport.CreateService") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -602,45 +595,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{parent=projects/*/locations/*}/services", - "body": "service", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseCreateService._get_http_options() + ) request, metadata = self._interceptor.pre_create_service(request, metadata) - pb_request = gcr_service.CreateServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseServicesRestTransport._BaseCreateService._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServicesRestTransport._BaseCreateService._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseCreateService._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServicesRestTransport._CreateService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -654,19 +638,33 @@ def __call__( resp = self._interceptor.post_create_service(resp) return resp - class _DeleteService(ServicesRestStub): + class _DeleteService( + _BaseServicesRestTransport._BaseDeleteService, ServicesRestStub + ): def __hash__(self): - return hash("DeleteService") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.DeleteService") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -696,38 +694,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/services/*}", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseDeleteService._get_http_options() + ) request, metadata = self._interceptor.pre_delete_service(request, metadata) - pb_request = service.DeleteServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseDeleteService._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseDeleteService._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ServicesRestTransport._DeleteService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -741,19 +732,31 @@ def __call__( resp = self._interceptor.post_delete_service(resp) return resp - class _GetIamPolicy(ServicesRestStub): + class _GetIamPolicy(_BaseServicesRestTransport._BaseGetIamPolicy, ServicesRestStub): def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -854,38 +857,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{resource=projects/*/locations/*/services/*}:getIamPolicy", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ServicesRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -901,19 +897,31 @@ def __call__( resp = self._interceptor.post_get_iam_policy(resp) return resp - class _GetService(ServicesRestStub): + class _GetService(_BaseServicesRestTransport._BaseGetService, ServicesRestStub): def __hash__(self): - return hash("GetService") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.GetService") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -949,38 +957,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/services/*}", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseGetService._get_http_options() + ) request, metadata = self._interceptor.pre_get_service(request, metadata) - pb_request = service.GetServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseGetService._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseGetService._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ServicesRestTransport._GetService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -996,19 +997,31 @@ def __call__( resp = self._interceptor.post_get_service(resp) return resp - class _ListServices(ServicesRestStub): + class _ListServices(_BaseServicesRestTransport._BaseListServices, ServicesRestStub): def __hash__(self): - return hash("ListServices") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.ListServices") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -1037,38 +1050,31 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*}/services", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseListServices._get_http_options() + ) request, metadata = self._interceptor.pre_list_services(request, metadata) - pb_request = service.ListServicesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseListServices._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseListServices._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = ServicesRestTransport._ListServices._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1084,19 +1090,32 @@ def __call__( resp = self._interceptor.post_list_services(resp) return resp - class _SetIamPolicy(ServicesRestStub): + class _SetIamPolicy(_BaseServicesRestTransport._BaseSetIamPolicy, ServicesRestStub): def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1197,45 +1216,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{resource=projects/*/locations/*/services/*}:setIamPolicy", - "body": "*", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseServicesRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServicesRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServicesRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1251,19 +1261,34 @@ def __call__( resp = self._interceptor.post_set_iam_policy(resp) return resp - class _TestIamPermissions(ServicesRestStub): + class _TestIamPermissions( + _BaseServicesRestTransport._BaseTestIamPermissions, ServicesRestStub + ): def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1289,47 +1314,34 @@ def __call__( Response message for ``TestIamPermissions`` method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{resource=projects/*/locations/*/services/*}:testIamPermissions", - "body": "*", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseTestIamPermissions._get_http_options() + ) request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = _BaseServicesRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServicesRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) + query_params = _BaseServicesRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServicesRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1345,19 +1357,34 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp - class _UpdateService(ServicesRestStub): + class _UpdateService( + _BaseServicesRestTransport._BaseUpdateService, ServicesRestStub + ): def __hash__(self): - return hash("UpdateService") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("ServicesRestTransport.UpdateService") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response def __call__( self, @@ -1387,45 +1414,36 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "patch", - "uri": "/v2/{service.name=projects/*/locations/*/services/*}", - "body": "service", - }, - ] + http_options = ( + _BaseServicesRestTransport._BaseUpdateService._get_http_options() + ) request, metadata = self._interceptor.pre_update_service(request, metadata) - pb_request = gcr_service.UpdateServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body + transcoded_request = ( + _BaseServicesRestTransport._BaseUpdateService._get_transcoded_request( + http_options, request + ) + ) - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True + body = _BaseServicesRestTransport._BaseUpdateService._get_request_body_json( + transcoded_request ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseServicesRestTransport._BaseUpdateService._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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, + response = ServicesRestTransport._UpdateService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1508,7 +1526,34 @@ def update_service( def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(ServicesRestStub): + class _DeleteOperation( + _BaseServicesRestTransport._BaseDeleteOperation, ServicesRestStub + ): + def __hash__(self): + return hash("ServicesRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -1529,34 +1574,33 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseServicesRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseServicesRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ServicesRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1570,7 +1614,32 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(ServicesRestStub): + class _GetOperation(_BaseServicesRestTransport._BaseGetOperation, ServicesRestStub): + def __hash__(self): + return hash("ServicesRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -1594,32 +1663,31 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseServicesRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseServicesRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ServicesRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1627,8 +1695,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -1636,7 +1705,34 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(ServicesRestStub): + class _ListOperations( + _BaseServicesRestTransport._BaseListOperations, ServicesRestStub + ): + def __hash__(self): + return hash("ServicesRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -1660,32 +1756,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseServicesRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseServicesRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseServicesRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = ServicesRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1693,8 +1788,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -1702,7 +1798,35 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(ServicesRestStub): + class _WaitOperation( + _BaseServicesRestTransport._BaseWaitOperation, ServicesRestStub + ): + def __hash__(self): + return hash("ServicesRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -1726,35 +1850,36 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = ( + _BaseServicesRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseServicesRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseServicesRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseServicesRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = ServicesRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1762,8 +1887,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest_base.py new file mode 100644 index 000000000000..c94eda0e86de --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/services/transports/rest_base.py @@ -0,0 +1,620 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import service +from google.cloud.run_v2.types import service as gcr_service + +from .base import DEFAULT_CLIENT_INFO, ServicesTransport + + +class _BaseServicesRestTransport(ServicesTransport): + """Base REST backend transport for Services. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseCreateService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serviceId": "", + } + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/services", + "body": "service", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcr_service.CreateServiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseCreateService._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/services/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteServiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseDeleteService._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseGetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/services/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetServiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseGetService._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServices: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/services", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListServicesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseListServices._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseSetIamPolicy._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=projects/*/locations/*/services/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseTestIamPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{service.name=projects/*/locations/*/services/*}", + "body": "service", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcr_service.UpdateServiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseServicesRestTransport._BaseUpdateService._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseServicesRestTransport",) diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/async_client.py index 381fe4df1417..90a4d16db39e 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/async_client.py @@ -525,11 +525,7 @@ async def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -582,11 +578,7 @@ async def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -643,11 +635,7 @@ async def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -703,11 +691,7 @@ async def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self.transport._wrapped_methods[self._client._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/client.py index 819044044ce2..d7d637275317 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/client.py @@ -1085,11 +1085,7 @@ def list_operations( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.list_operations] # Certain fields should be provided within the metadata header; # add these here. @@ -1142,11 +1138,7 @@ def get_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.get_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1203,11 +1195,7 @@ def delete_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_operation] # Certain fields should be provided within the metadata header; # add these here. @@ -1263,11 +1251,7 @@ def wait_operation( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.wait_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._transport._wrapped_methods[self._transport.wait_operation] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/README.rst b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/README.rst new file mode 100644 index 000000000000..2bdc15d8a2cf --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TasksTransport` is the ABC for all transports. +- public child `TasksGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TasksGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTasksRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TasksRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/base.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/base.py index 0be53e6be474..38ea9bd77df2 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/base.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/base.py @@ -140,6 +140,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: gapic_v1.method.wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc.py index 17bad56f5673..b61173ea3cd5 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc.py @@ -313,7 +313,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc_asyncio.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc_asyncio.py index e5eeca5e7493..a8e1530d7302 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc_asyncio.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/grpc_asyncio.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import inspect from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -228,6 +229,9 @@ def __init__( ) # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) self._prep_wrapped_messages(client_info) @property @@ -293,21 +297,50 @@ def list_tasks( def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { - self.get_task: gapic_v1.method_async.wrap_method( + self.get_task: self._wrap_method( self.get_task, default_timeout=None, client_info=client_info, ), - self.list_tasks: gapic_v1.method_async.wrap_method( + self.list_tasks: self._wrap_method( self.list_tasks, default_timeout=None, client_info=client_info, ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + self.wait_operation: self._wrap_method( + self.wait_operation, + default_timeout=None, + client_info=client_info, + ), } + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + def close(self): return self.grpc_channel.close() + @property + def kind(self) -> str: + return "grpc_asyncio" + @property def delete_operation( self, @@ -334,7 +367,7 @@ def wait_operation( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_operation" not in self._stubs: + if "wait_operation" not in self._stubs: self._stubs["wait_operation"] = self.grpc_channel.unary_unary( "/google.longrunning.Operations/WaitOperation", request_serializer=operations_pb2.WaitOperationRequest.SerializeToString, diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest.py index 17a26fed9533..e146efdc54d9 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest.py @@ -16,34 +16,30 @@ import dataclasses import json # type: ignore -import re from typing import Any, 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 gapic_v1, rest_helpers, rest_streaming 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -import grpc # type: ignore from requests import __version__ as requests_version +from google.cloud.run_v2.types import task + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTasksRestTransport + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from google.cloud.run_v2.types import task - -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO -from .base import TasksTransport - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, @@ -226,8 +222,8 @@ class TasksRestStub: _interceptor: TasksRestInterceptor -class TasksRestTransport(TasksTransport): - """REST backend transport for Tasks. +class TasksRestTransport(_BaseTasksRestTransport): + """REST backend synchronous transport for Tasks. Cloud Run Task Control Plane API. @@ -236,7 +232,6 @@ class TasksRestTransport(TasksTransport): and call it. It sends JSON representations of protocol buffers over HTTP/1.1 - """ def __init__( @@ -290,21 +285,12 @@ def __init__( # 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, + url_scheme=url_scheme, api_audience=api_audience, ) self._session = AuthorizedSession( @@ -315,19 +301,31 @@ def __init__( self._interceptor = interceptor or TasksRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetTask(TasksRestStub): + class _GetTask(_BaseTasksRestTransport._BaseGetTask, TasksRestStub): def __hash__(self): - return hash("GetTask") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TasksRestTransport.GetTask") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -356,38 +354,27 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*/tasks/*}", - }, - ] + http_options = _BaseTasksRestTransport._BaseGetTask._get_http_options() request, metadata = self._interceptor.pre_get_task(request, metadata) - pb_request = task.GetTaskRequest.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"], - use_integers_for_enums=True, + transcoded_request = ( + _BaseTasksRestTransport._BaseGetTask._get_transcoded_request( + http_options, request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - query_params["$alt"] = "json;enum-encoding=int" + # Jsonify the query params + query_params = _BaseTasksRestTransport._BaseGetTask._get_query_params_json( + transcoded_request + ) # 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), + response = TasksRestTransport._GetTask._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -403,19 +390,31 @@ def __call__( resp = self._interceptor.post_get_task(resp) return resp - class _ListTasks(TasksRestStub): + class _ListTasks(_BaseTasksRestTransport._BaseListTasks, TasksRestStub): def __hash__(self): - return hash("ListTasks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @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 - } + return hash("TasksRestTransport.ListTasks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response def __call__( self, @@ -444,38 +443,29 @@ def __call__( """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{parent=projects/*/locations/*/jobs/*/executions/*}/tasks", - }, - ] + http_options = _BaseTasksRestTransport._BaseListTasks._get_http_options() request, metadata = self._interceptor.pre_list_tasks(request, metadata) - pb_request = task.ListTasksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTasksRestTransport._BaseListTasks._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, + query_params = ( + _BaseTasksRestTransport._BaseListTasks._get_query_params_json( + transcoded_request ) ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" # 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), + response = TasksRestTransport._ListTasks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -507,7 +497,32 @@ def list_tasks(self) -> Callable[[task.ListTasksRequest], task.ListTasksResponse def delete_operation(self): return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(TasksRestStub): + class _DeleteOperation(_BaseTasksRestTransport._BaseDeleteOperation, TasksRestStub): + def __hash__(self): + return hash("TasksRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.DeleteOperationRequest, @@ -528,34 +543,33 @@ def __call__( sent along with the request as metadata. """ - http_options: List[Dict[str, str]] = [ - { - "method": "delete", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = ( + _BaseTasksRestTransport._BaseDeleteOperation._get_http_options() + ) request, metadata = self._interceptor.pre_delete_operation( request, metadata ) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTasksRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTasksRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TasksRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -569,7 +583,32 @@ def __call__( def get_operation(self): return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(TasksRestStub): + class _GetOperation(_BaseTasksRestTransport._BaseGetOperation, TasksRestStub): + def __hash__(self): + return hash("TasksRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.GetOperationRequest, @@ -593,32 +632,29 @@ def __call__( operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*/operations/*}", - }, - ] - + http_options = _BaseTasksRestTransport._BaseGetOperation._get_http_options() request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTasksRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTasksRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TasksRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -626,8 +662,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) return resp @@ -635,7 +672,32 @@ def __call__( def list_operations(self): return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(TasksRestStub): + class _ListOperations(_BaseTasksRestTransport._BaseListOperations, TasksRestStub): + def __hash__(self): + return hash("TasksRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + def __call__( self, request: operations_pb2.ListOperationsRequest, @@ -659,32 +721,31 @@ def __call__( operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v2/{name=projects/*/locations/*}/operations", - }, - ] - + http_options = ( + _BaseTasksRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) - - uri = transcoded_request["uri"] - method = transcoded_request["method"] + transcoded_request = ( + _BaseTasksRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTasksRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + ) # 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), + response = TasksRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -692,8 +753,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) return resp @@ -701,7 +763,33 @@ def __call__( def wait_operation(self): return self._WaitOperation(self._session, self._host, self._interceptor) # type: ignore - class _WaitOperation(TasksRestStub): + class _WaitOperation(_BaseTasksRestTransport._BaseWaitOperation, TasksRestStub): + def __hash__(self): + return hash("TasksRestTransport.WaitOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + def __call__( self, request: operations_pb2.WaitOperationRequest, @@ -725,35 +813,36 @@ def __call__( operations_pb2.Operation: Response from WaitOperation method. """ - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", - "body": "*", - }, - ] - + http_options = ( + _BaseTasksRestTransport._BaseWaitOperation._get_http_options() + ) request, metadata = self._interceptor.pre_wait_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode(http_options, **request_kwargs) + transcoded_request = ( + _BaseTasksRestTransport._BaseWaitOperation._get_transcoded_request( + http_options, request + ) + ) - body = json.dumps(transcoded_request["body"]) - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body = _BaseTasksRestTransport._BaseWaitOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request["query_params"])) + query_params = ( + _BaseTasksRestTransport._BaseWaitOperation._get_query_params_json( + transcoded_request + ) + ) # 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), - data=body, + response = TasksRestTransport._WaitOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -761,8 +850,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + content = response.content.decode("utf-8") resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = json_format.Parse(content, resp) resp = self._interceptor.post_wait_operation(resp) return resp diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest_base.py b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest_base.py new file mode 100644 index 000000000000..f57566ea7e77 --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/services/tasks/transports/rest_base.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.run_v2.types import task + +from .base import DEFAULT_CLIENT_INFO, TasksTransport + + +class _BaseTasksRestTransport(TasksTransport): + """Base REST backend transport for Tasks. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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 + """ + + def __init__( + self, + *, + host: str = "run.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'run.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + 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 + 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, + ) + + class _BaseGetTask: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/jobs/*/executions/*/tasks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = task.GetTaskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTasksRestTransport._BaseGetTask._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTasks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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 + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/jobs/*/executions/*}/tasks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = task.ListTasksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseTasksRestTransport._BaseListTasks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseWaitOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:wait", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseTasksRestTransport",) diff --git a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json index e61dbbb79b79..84a8ca294789 100644 --- a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json +++ b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-run", - "version": "0.10.9" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-run/setup.py b/packages/google-cloud-run/setup.py index 1b5253ff3bda..489de060f25b 100644 --- a/packages/google-cloud-run/setup.py +++ b/packages/google-cloud-run/setup.py @@ -47,6 +47,7 @@ "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -89,6 +90,7 @@ packages=packages, python_requires=">=3.7", install_requires=dependencies, + extras_require=extras, include_package_data=True, zip_safe=False, ) diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_builds.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_builds.py index dd13d86db489..4af7b41956aa 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_builds.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_builds.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -36,14 +53,6 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore 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.run_v2.services.builds import ( BuildsAsyncClient, @@ -53,10 +62,24 @@ from google.cloud.run_v2.types import build +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1088,25 +1111,6 @@ def test_submit_build(request_type, transport: str = "grpc"): assert response.base_image_warning == "base_image_warning_value" -def test_submit_build_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.submit_build), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.submit_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == build.SubmitBuildRequest() - - def test_submit_build_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1176,30 +1180,6 @@ def test_submit_build_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_submit_build_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.submit_build), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - build.SubmitBuildResponse( - base_image_uri="base_image_uri_value", - base_image_warning="base_image_warning_value", - ) - ) - response = await client.submit_build() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == build.SubmitBuildRequest() - - @pytest.mark.asyncio async def test_submit_build_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1208,7 +1188,7 @@ async def test_submit_build_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1247,7 +1227,7 @@ async def test_submit_build_async( transport: str = "grpc_asyncio", request_type=build.SubmitBuildRequest ): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1315,7 +1295,7 @@ def test_submit_build_field_headers(): @pytest.mark.asyncio async def test_submit_build_field_headers_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1344,48 +1324,6 @@ async def test_submit_build_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - build.SubmitBuildRequest, - dict, - ], -) -def test_submit_build_rest(request_type): - client = BuildsClient( - 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 = build.SubmitBuildResponse( - base_image_uri="base_image_uri_value", - base_image_warning="base_image_warning_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = build.SubmitBuildResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.submit_build(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, build.SubmitBuildResponse) - assert response.base_image_uri == "base_image_uri_value" - assert response.base_image_warning == "base_image_warning_value" - - def test_submit_build_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1517,89 +1455,6 @@ def test_submit_build_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_submit_build_rest_interceptors(null_interceptor): - transport = transports.BuildsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BuildsRestInterceptor(), - ) - client = BuildsClient(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.BuildsRestInterceptor, "post_submit_build" - ) as post, mock.patch.object( - transports.BuildsRestInterceptor, "pre_submit_build" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = build.SubmitBuildRequest.pb(build.SubmitBuildRequest()) - 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 = build.SubmitBuildResponse.to_json( - build.SubmitBuildResponse() - ) - - request = build.SubmitBuildRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = build.SubmitBuildResponse() - - client.submit_build( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_submit_build_rest_bad_request( - transport: str = "rest", request_type=build.SubmitBuildRequest -): - client = BuildsClient( - 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.submit_build(request) - - -def test_submit_build_rest_error(): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.BuildsGrpcTransport( @@ -1692,91 +1547,543 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = BuildsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), +def test_transport_kind_grpc(): + transport = BuildsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() ) - assert transport.kind == transport_name + assert transport.kind == "grpc" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_initialize_client_w_grpc(): client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - assert isinstance( - client.transport, - transports.BuildsGrpcTransport, + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_submit_build_empty_call_grpc(): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.submit_build), "__call__") as call: + call.return_value = build.SubmitBuildResponse() + client.submit_build(request=None) -def test_builds_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BuildsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = build.SubmitBuildRequest() + assert args[0] == request_msg -def test_builds_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.run_v2.services.builds.transports.BuildsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.BuildsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "submit_build", - "get_operation", - "wait_operation", - "delete_operation", - "list_operations", +def test_transport_kind_grpc_asyncio(): + transport = BuildsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + assert transport.kind == "grpc_asyncio" - 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_initialize_client_w_grpc_asyncio(): + client = BuildsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_builds_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.run_v2.services.builds.transports.BuildsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BuildsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_submit_build_empty_call_grpc_asyncio(): + client = BuildsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.submit_build), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + build.SubmitBuildResponse( + base_image_uri="base_image_uri_value", + base_image_warning="base_image_warning_value", + ) + ) + await client.submit_build(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = build.SubmitBuildRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BuildsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_submit_build_rest_bad_request(request_type=build.SubmitBuildRequest): + client = BuildsClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.submit_build(request) + + +@pytest.mark.parametrize( + "request_type", + [ + build.SubmitBuildRequest, + dict, + ], +) +def test_submit_build_rest_call_success(request_type): + client = BuildsClient( + 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 = build.SubmitBuildResponse( + base_image_uri="base_image_uri_value", + base_image_warning="base_image_warning_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = build.SubmitBuildResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.submit_build(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, build.SubmitBuildResponse) + assert response.base_image_uri == "base_image_uri_value" + assert response.base_image_warning == "base_image_warning_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_submit_build_rest_interceptors(null_interceptor): + transport = transports.BuildsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BuildsRestInterceptor(), + ) + client = BuildsClient(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.BuildsRestInterceptor, "post_submit_build" + ) as post, mock.patch.object( + transports.BuildsRestInterceptor, "pre_submit_build" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = build.SubmitBuildRequest.pb(build.SubmitBuildRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = build.SubmitBuildResponse.to_json(build.SubmitBuildResponse()) + req.return_value.content = return_value + + request = build.SubmitBuildRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = build.SubmitBuildResponse() + + client.submit_build( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_submit_build_empty_call_rest(): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.submit_build), "__call__") as call: + client.submit_build(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = build.SubmitBuildRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BuildsGrpcTransport, + ) + + +def test_builds_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BuildsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_builds_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.run_v2.services.builds.transports.BuildsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BuildsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "submit_build", + "get_operation", + "wait_operation", + "delete_operation", + "list_operations", + ) + 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_builds_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.run_v2.services.builds.transports.BuildsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BuildsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -2144,380 +2451,134 @@ def test_parse_worker_pool_path(): path = BuildsClient.worker_pool_path(**expected) # Check that the path construction is reversible. - actual = BuildsClient.parse_worker_pool_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = BuildsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = BuildsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = BuildsClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = BuildsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = BuildsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = BuildsClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = BuildsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = BuildsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = BuildsClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format( - project=project, - ) - actual = BuildsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = BuildsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = BuildsClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = BuildsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = BuildsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = BuildsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.BuildsTransport, "_prep_wrapped_messages" - ) as prep: - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.BuildsTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = BuildsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + actual = BuildsClient.parse_worker_pool_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + actual = BuildsClient.common_billing_account_path(billing_account) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = BuildsClient.common_billing_account_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + # Check that the path construction is reversible. + actual = BuildsClient.parse_common_billing_account_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, ) + actual = BuildsClient.common_folder_path(folder) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # 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.list_operations(request) +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = BuildsClient.common_folder_path(**expected) + # Check that the path construction is reversible. + actual = BuildsClient.parse_common_folder_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = BuildsClient.common_organization_path(organization) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = BuildsClient.common_organization_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + # Check that the path construction is reversible. + actual = BuildsClient.parse_common_organization_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, ) + actual = BuildsClient.common_project_path(project) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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.wait_operation(request) +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = BuildsClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = BuildsClient.parse_common_project_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + actual = BuildsClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = BuildsClient.common_location_path(**expected) - response = client.wait_operation(request) + # Check that the path construction is reversible. + actual = BuildsClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.BuildsTransport, "_prep_wrapped_messages" + ) as prep: + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.BuildsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = BuildsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -2547,7 +2608,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2600,7 +2661,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2645,7 +2706,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -2686,7 +2747,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2741,7 +2802,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2788,7 +2849,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -2831,7 +2892,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2886,7 +2947,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2933,7 +2994,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -2976,7 +3037,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3031,7 +3092,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3078,7 +3139,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = BuildsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -3094,22 +3155,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = BuildsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = BuildsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = BuildsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_executions.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_executions.py index 1d10325f99e9..f0dc86f128e6 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_executions.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_executions.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import launch_stage_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -46,15 +63,7 @@ from google.cloud.location import locations_pb2 from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.run_v2.services.executions import ( ExecutionsAsyncClient, @@ -65,10 +74,24 @@ from google.cloud.run_v2.types import condition, execution, task_template +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1157,25 +1180,6 @@ def test_get_execution(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_execution_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_execution), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.GetExecutionRequest() - - def test_get_execution_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1239,45 +1243,6 @@ def test_get_execution_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_execution_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_execution), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - execution.Execution( - name="name_value", - uid="uid_value", - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - job="job_value", - parallelism=1174, - task_count=1083, - reconciling=True, - observed_generation=2021, - running_count=1417, - succeeded_count=1581, - failed_count=1261, - cancelled_count=1571, - retried_count=1399, - log_uri="log_uri_value", - satisfies_pzs=True, - etag="etag_value", - ) - ) - response = await client.get_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.GetExecutionRequest() - - @pytest.mark.asyncio async def test_get_execution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1286,7 +1251,7 @@ async def test_get_execution_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1325,7 +1290,7 @@ async def test_get_execution_async( transport: str = "grpc_asyncio", request_type=execution.GetExecutionRequest ): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1423,7 +1388,7 @@ def test_get_execution_field_headers(): @pytest.mark.asyncio async def test_get_execution_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1491,7 +1456,7 @@ def test_get_execution_flattened_error(): @pytest.mark.asyncio async def test_get_execution_flattened_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1518,7 +1483,7 @@ async def test_get_execution_flattened_async(): @pytest.mark.asyncio async def test_get_execution_flattened_error_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1566,25 +1531,6 @@ def test_list_executions(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_executions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_executions), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_executions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.ListExecutionsRequest() - - def test_list_executions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1650,29 +1596,6 @@ def test_list_executions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_executions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_executions), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - execution.ListExecutionsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_executions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.ListExecutionsRequest() - - @pytest.mark.asyncio async def test_list_executions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1681,7 +1604,7 @@ async def test_list_executions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1720,7 +1643,7 @@ async def test_list_executions_async( transport: str = "grpc_asyncio", request_type=execution.ListExecutionsRequest ): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1786,7 +1709,7 @@ def test_list_executions_field_headers(): @pytest.mark.asyncio async def test_list_executions_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1856,7 +1779,7 @@ def test_list_executions_flattened_error(): @pytest.mark.asyncio async def test_list_executions_flattened_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1885,7 +1808,7 @@ async def test_list_executions_flattened_async(): @pytest.mark.asyncio async def test_list_executions_flattened_error_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1995,7 +1918,7 @@ def test_list_executions_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_executions_async_pager(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2045,7 +1968,7 @@ async def test_list_executions_async_pager(): @pytest.mark.asyncio async def test_list_executions_async_pages(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2124,25 +2047,6 @@ def test_delete_execution(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_execution_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_execution), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.DeleteExecutionRequest() - - def test_delete_execution_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2215,27 +2119,6 @@ def test_delete_execution_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_execution_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_execution), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.DeleteExecutionRequest() - - @pytest.mark.asyncio async def test_delete_execution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2244,7 +2127,7 @@ async def test_delete_execution_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2288,7 +2171,7 @@ async def test_delete_execution_async( transport: str = "grpc_asyncio", request_type=execution.DeleteExecutionRequest ): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2351,7 +2234,7 @@ def test_delete_execution_field_headers(): @pytest.mark.asyncio async def test_delete_execution_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2421,7 +2304,7 @@ def test_delete_execution_flattened_error(): @pytest.mark.asyncio async def test_delete_execution_flattened_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2450,7 +2333,7 @@ async def test_delete_execution_flattened_async(): @pytest.mark.asyncio async def test_delete_execution_flattened_error_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2495,25 +2378,6 @@ def test_cancel_execution(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_cancel_execution_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_execution), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.cancel_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.CancelExecutionRequest() - - def test_cancel_execution_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2586,27 +2450,6 @@ def test_cancel_execution_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_cancel_execution_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_execution), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.cancel_execution() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == execution.CancelExecutionRequest() - - @pytest.mark.asyncio async def test_cancel_execution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2615,7 +2458,7 @@ async def test_cancel_execution_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2659,7 +2502,7 @@ async def test_cancel_execution_async( transport: str = "grpc_asyncio", request_type=execution.CancelExecutionRequest ): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2722,7 +2565,7 @@ def test_cancel_execution_field_headers(): @pytest.mark.asyncio async def test_cancel_execution_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -2792,7 +2635,7 @@ def test_cancel_execution_flattened_error(): @pytest.mark.asyncio async def test_cancel_execution_flattened_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2821,7 +2664,7 @@ async def test_cancel_execution_flattened_async(): @pytest.mark.asyncio async def test_cancel_execution_flattened_error_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2833,108 +2676,34 @@ async def test_cancel_execution_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - execution.GetExecutionRequest, - dict, - ], -) -def test_get_execution_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_execution_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - request = request_type(**request_init) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # 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 = execution.Execution( - name="name_value", - uid="uid_value", - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - job="job_value", - parallelism=1174, - task_count=1083, - reconciling=True, - observed_generation=2021, - running_count=1417, - succeeded_count=1581, - failed_count=1261, - cancelled_count=1571, - retried_count=1399, - log_uri="log_uri_value", - satisfies_pzs=True, - etag="etag_value", + # Ensure method has been cached + assert client._transport.get_execution in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = execution.Execution.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request = {} + client.get_execution(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_execution(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, execution.Execution) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.generation == 1068 - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.job == "job_value" - assert response.parallelism == 1174 - assert response.task_count == 1083 - assert response.reconciling is True - assert response.observed_generation == 2021 - assert response.running_count == 1417 - assert response.succeeded_count == 1581 - assert response.failed_count == 1261 - assert response.cancelled_count == 1571 - assert response.retried_count == 1399 - assert response.log_uri == "log_uri_value" - assert response.satisfies_pzs is True - assert response.etag == "etag_value" - - -def test_get_execution_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_execution in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_execution] = mock_rpc - - request = {} - client.get_execution(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 client.get_execution(request) @@ -3024,85 +2793,6 @@ def test_get_execution_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_execution_rest_interceptors(null_interceptor): - transport = transports.ExecutionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ExecutionsRestInterceptor(), - ) - client = ExecutionsClient(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.ExecutionsRestInterceptor, "post_get_execution" - ) as post, mock.patch.object( - transports.ExecutionsRestInterceptor, "pre_get_execution" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = execution.GetExecutionRequest.pb(execution.GetExecutionRequest()) - 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 = execution.Execution.to_json(execution.Execution()) - - request = execution.GetExecutionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = execution.Execution() - - client.get_execution( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_execution_rest_bad_request( - transport: str = "rest", request_type=execution.GetExecutionRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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_execution(request) - - def test_get_execution_rest_flattened(): client = ExecutionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3162,52 +2852,6 @@ def test_get_execution_rest_flattened_error(transport: str = "rest"): ) -def test_get_execution_rest_error(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - execution.ListExecutionsRequest, - dict, - ], -) -def test_list_executions_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/jobs/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 = execution.ListExecutionsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = execution.ListExecutionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_executions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExecutionsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_executions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3344,87 +2988,6 @@ def test_list_executions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_executions_rest_interceptors(null_interceptor): - transport = transports.ExecutionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ExecutionsRestInterceptor(), - ) - client = ExecutionsClient(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.ExecutionsRestInterceptor, "post_list_executions" - ) as post, mock.patch.object( - transports.ExecutionsRestInterceptor, "pre_list_executions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = execution.ListExecutionsRequest.pb( - execution.ListExecutionsRequest() - ) - 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 = execution.ListExecutionsResponse.to_json( - execution.ListExecutionsResponse() - ) - - request = execution.ListExecutionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = execution.ListExecutionsResponse() - - client.list_executions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_executions_rest_bad_request( - transport: str = "rest", request_type=execution.ListExecutionsRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/jobs/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.list_executions(request) - - def test_list_executions_rest_flattened(): client = ExecutionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3543,43 +3106,6 @@ def test_list_executions_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - execution.DeleteExecutionRequest, - dict, - ], -) -def test_delete_execution_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_execution(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_execution_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3717,91 +3243,6 @@ def test_delete_execution_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_execution_rest_interceptors(null_interceptor): - transport = transports.ExecutionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ExecutionsRestInterceptor(), - ) - client = ExecutionsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ExecutionsRestInterceptor, "post_delete_execution" - ) as post, mock.patch.object( - transports.ExecutionsRestInterceptor, "pre_delete_execution" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = execution.DeleteExecutionRequest.pb( - execution.DeleteExecutionRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = execution.DeleteExecutionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_execution( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_execution_rest_bad_request( - transport: str = "rest", request_type=execution.DeleteExecutionRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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.delete_execution(request) - - def test_delete_execution_rest_flattened(): client = ExecutionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3859,49 +3300,6 @@ def test_delete_execution_rest_flattened_error(transport: str = "rest"): ) -def test_delete_execution_rest_error(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - execution.CancelExecutionRequest, - dict, - ], -) -def test_cancel_execution_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.cancel_execution(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_cancel_execution_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4025,91 +3423,6 @@ def test_cancel_execution_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_cancel_execution_rest_interceptors(null_interceptor): - transport = transports.ExecutionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ExecutionsRestInterceptor(), - ) - client = ExecutionsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ExecutionsRestInterceptor, "post_cancel_execution" - ) as post, mock.patch.object( - transports.ExecutionsRestInterceptor, "pre_cancel_execution" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = execution.CancelExecutionRequest.pb( - execution.CancelExecutionRequest() - ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = execution.CancelExecutionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.cancel_execution( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_cancel_execution_rest_bad_request( - transport: str = "rest", request_type=execution.CancelExecutionRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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.cancel_execution(request) - - def test_cancel_execution_rest_flattened(): client = ExecutionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4167,12 +3480,6 @@ def test_cancel_execution_rest_flattened_error(transport: str = "rest"): ) -def test_cancel_execution_rest_error(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ExecutionsGrpcTransport( @@ -4265,18 +3572,1095 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ExecutionsClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = ExecutionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_execution), "__call__") as call: + call.return_value = execution.Execution() + client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_executions_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_executions), "__call__") as call: + call.return_value = execution.ListExecutionsResponse() + client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_execution), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.DeleteExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_execution_empty_call_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.cancel_execution), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ExecutionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_execution), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + execution.Execution( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + job="job_value", + parallelism=1174, + task_count=1083, + reconciling=True, + observed_generation=2021, + running_count=1417, + succeeded_count=1581, + failed_count=1261, + cancelled_count=1571, + retried_count=1399, + log_uri="log_uri_value", + satisfies_pzs=True, + etag="etag_value", + ) + ) + await client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_executions_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_executions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + execution.ListExecutionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_execution), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.DeleteExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_cancel_execution_empty_call_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.cancel_execution), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ExecutionsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_execution_rest_bad_request(request_type=execution.GetExecutionRequest): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_execution(request) + + +@pytest.mark.parametrize( + "request_type", + [ + execution.GetExecutionRequest, + dict, + ], +) +def test_get_execution_rest_call_success(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = execution.Execution( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + job="job_value", + parallelism=1174, + task_count=1083, + reconciling=True, + observed_generation=2021, + running_count=1417, + succeeded_count=1581, + failed_count=1261, + cancelled_count=1571, + retried_count=1399, + log_uri="log_uri_value", + satisfies_pzs=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = execution.Execution.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_execution(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, execution.Execution) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.job == "job_value" + assert response.parallelism == 1174 + assert response.task_count == 1083 + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.running_count == 1417 + assert response.succeeded_count == 1581 + assert response.failed_count == 1261 + assert response.cancelled_count == 1571 + assert response.retried_count == 1399 + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_execution_rest_interceptors(null_interceptor): + transport = transports.ExecutionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ExecutionsRestInterceptor(), + ) + client = ExecutionsClient(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.ExecutionsRestInterceptor, "post_get_execution" + ) as post, mock.patch.object( + transports.ExecutionsRestInterceptor, "pre_get_execution" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = execution.GetExecutionRequest.pb(execution.GetExecutionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = execution.Execution.to_json(execution.Execution()) + req.return_value.content = return_value + + request = execution.GetExecutionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = execution.Execution() + + client.get_execution( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_executions_rest_bad_request(request_type=execution.ListExecutionsRequest): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_executions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + execution.ListExecutionsRequest, + dict, + ], +) +def test_list_executions_rest_call_success(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/jobs/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 = execution.ListExecutionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = execution.ListExecutionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_executions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExecutionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_executions_rest_interceptors(null_interceptor): + transport = transports.ExecutionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ExecutionsRestInterceptor(), + ) + client = ExecutionsClient(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.ExecutionsRestInterceptor, "post_list_executions" + ) as post, mock.patch.object( + transports.ExecutionsRestInterceptor, "pre_list_executions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = execution.ListExecutionsRequest.pb( + execution.ListExecutionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = execution.ListExecutionsResponse.to_json( + execution.ListExecutionsResponse() + ) + req.return_value.content = return_value + + request = execution.ListExecutionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = execution.ListExecutionsResponse() + + client.list_executions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_execution_rest_bad_request( + request_type=execution.DeleteExecutionRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_execution(request) + + +@pytest.mark.parametrize( + "request_type", + [ + execution.DeleteExecutionRequest, + dict, + ], +) +def test_delete_execution_rest_call_success(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_execution(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_execution_rest_interceptors(null_interceptor): + transport = transports.ExecutionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ExecutionsRestInterceptor(), + ) + client = ExecutionsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ExecutionsRestInterceptor, "post_delete_execution" + ) as post, mock.patch.object( + transports.ExecutionsRestInterceptor, "pre_delete_execution" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = execution.DeleteExecutionRequest.pb( + execution.DeleteExecutionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = execution.DeleteExecutionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_execution( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_cancel_execution_rest_bad_request( + request_type=execution.CancelExecutionRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.cancel_execution(request) + + +@pytest.mark.parametrize( + "request_type", + [ + execution.CancelExecutionRequest, + dict, + ], +) +def test_cancel_execution_rest_call_success(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.cancel_execution(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_execution_rest_interceptors(null_interceptor): + transport = transports.ExecutionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ExecutionsRestInterceptor(), + ) + client = ExecutionsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ExecutionsRestInterceptor, "post_cancel_execution" + ) as post, mock.patch.object( + transports.ExecutionsRestInterceptor, "pre_cancel_execution" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = execution.CancelExecutionRequest.pb( + execution.CancelExecutionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = execution.CancelExecutionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.cancel_execution( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_execution_empty_call_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_execution), "__call__") as call: + client.get_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.GetExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_executions_empty_call_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_executions), "__call__") as call: + client.list_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.ListExecutionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_execution_empty_call_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_execution), "__call__") as call: + client.delete_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.DeleteExecutionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_cancel_execution_empty_call_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.cancel_execution), "__call__") as call: + client.cancel_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = execution.CancelExecutionRequest() + + assert args[0] == request_msg + + +def test_executions_rest_lro_client(): + client = ExecutionsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -4517,23 +4901,6 @@ def test_executions_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_executions_rest_lro_client(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -4921,375 +5288,129 @@ def test_parse_secret_version_path(): def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = ExecutionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ExecutionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = ExecutionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ExecutionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = ExecutionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ExecutionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, - ) - actual = ExecutionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ExecutionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = ExecutionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ExecutionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ExecutionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.ExecutionsTransport, "_prep_wrapped_messages" - ) as prep: - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.ExecutionsTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = ExecutionsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ExecutionsClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ExecutionsClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ExecutionsClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ExecutionsClient.common_folder_path(**expected) -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_folder_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = ExecutionsClient.common_organization_path(organization) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ExecutionsClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = ExecutionsClient.common_project_path(project) + assert expected == actual - response = client.list_operations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ExecutionsClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_project_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = ExecutionsClient.common_location_path(project, location) + assert expected == actual - # 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.wait_operation(request) +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ExecutionsClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = ExecutionsClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.wait_operation(request) + with mock.patch.object( + transports.ExecutionsTransport, "_prep_wrapped_messages" + ) as prep: + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + with mock.patch.object( + transports.ExecutionsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ExecutionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -5319,7 +5440,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5372,7 +5493,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5417,7 +5538,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -5458,7 +5579,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5513,7 +5634,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5560,7 +5681,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -5603,7 +5724,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5658,7 +5779,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5705,7 +5826,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -5748,7 +5869,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5803,7 +5924,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5850,7 +5971,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ExecutionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -5866,22 +5987,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ExecutionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ExecutionsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ExecutionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py index 7d6702058641..9bb413f05124 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import launch_stage_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -51,16 +68,8 @@ from google.oauth2 import service_account from google.protobuf import duration_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.type import expr_pb2 # type: ignore -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.run_v2.services.jobs import ( JobsAsyncClient, @@ -74,10 +83,24 @@ from google.cloud.run_v2.types import k8s_min, task_template, vendor_settings +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1085,25 +1108,6 @@ def test_create_job(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_job_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_job), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_job.CreateJobRequest() - - def test_create_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1174,34 +1178,13 @@ def test_create_job_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_job_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_job.CreateJobRequest() - - @pytest.mark.asyncio async def test_create_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1245,7 +1228,7 @@ async def test_create_job_async( transport: str = "grpc_asyncio", request_type=gcr_job.CreateJobRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1276,32 +1259,6 @@ async def test_create_job_async_from_dict(): await test_create_job_async(request_type=dict) -def test_create_job_routing_parameters(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_job.CreateJobRequest( - **{"parent": "projects/sample1/locations/sample2"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_job), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_create_job_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1353,7 +1310,7 @@ def test_create_job_flattened_error(): @pytest.mark.asyncio async def test_create_job_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1390,7 +1347,7 @@ async def test_create_job_flattened_async(): @pytest.mark.asyncio async def test_create_job_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1465,25 +1422,6 @@ def test_get_job(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_job_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_job), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.GetJobRequest() - - def test_get_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1547,48 +1485,13 @@ def test_get_job_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_job_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - job.Job( - name="name_value", - uid="uid_value", - generation=1068, - creator="creator_value", - last_modifier="last_modifier_value", - client="client_value", - client_version="client_version_value", - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - observed_generation=2021, - execution_count=1628, - reconciling=True, - satisfies_pzs=True, - etag="etag_value", - ) - ) - response = await client.get_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.GetJobRequest() - - @pytest.mark.asyncio async def test_get_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1627,7 +1530,7 @@ async def test_get_job_async( transport: str = "grpc_asyncio", request_type=job.GetJobRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1685,32 +1588,6 @@ async def test_get_job_async_from_dict(): await test_get_job_async(request_type=dict) -def test_get_job_routing_parameters(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = job.GetJobRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_job), "__call__") as call: - call.return_value = job.Job() - client.get_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_get_job_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1752,7 +1629,7 @@ def test_get_job_flattened_error(): @pytest.mark.asyncio async def test_get_job_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1779,7 +1656,7 @@ async def test_get_job_flattened_async(): @pytest.mark.asyncio async def test_get_job_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1827,25 +1704,6 @@ def test_list_jobs(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_jobs_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_jobs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.ListJobsRequest() - - def test_list_jobs_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1911,36 +1769,13 @@ def test_list_jobs_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_jobs_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - job.ListJobsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_jobs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.ListJobsRequest() - - @pytest.mark.asyncio async def test_list_jobs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1979,7 +1814,7 @@ async def test_list_jobs_async( transport: str = "grpc_asyncio", request_type=job.ListJobsRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2013,30 +1848,6 @@ async def test_list_jobs_async_from_dict(): await test_list_jobs_async(request_type=dict) -def test_list_jobs_routing_parameters(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = job.ListJobsRequest(**{"parent": "projects/sample1/locations/sample2"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: - call.return_value = job.ListJobsResponse() - client.list_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_list_jobs_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2078,7 +1889,7 @@ def test_list_jobs_flattened_error(): @pytest.mark.asyncio async def test_list_jobs_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2107,7 +1918,7 @@ async def test_list_jobs_flattened_async(): @pytest.mark.asyncio async def test_list_jobs_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2214,7 +2025,7 @@ def test_list_jobs_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_jobs_async_pager(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2264,7 +2075,7 @@ async def test_list_jobs_async_pager(): @pytest.mark.asyncio async def test_list_jobs_async_pages(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2343,25 +2154,6 @@ def test_update_job(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_job_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_job), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_job.UpdateJobRequest() - - def test_update_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2426,34 +2218,13 @@ def test_update_job_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_job_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_job.UpdateJobRequest() - - @pytest.mark.asyncio async def test_update_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2497,7 +2268,7 @@ async def test_update_job_async( transport: str = "grpc_asyncio", request_type=gcr_job.UpdateJobRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2528,46 +2299,20 @@ async def test_update_job_async_from_dict(): await test_update_job_async(request_type=dict) -def test_update_job_routing_parameters(): +def test_update_job_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_job.UpdateJobRequest( - **{"job": {"name": "projects/sample1/locations/sample2/sample3"}} - ) - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - client.update_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - -def test_update_job_flattened(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_job( - job=gcr_job.Job(name="name_value"), - ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_job( + job=gcr_job.Job(name="name_value"), + ) # Establish that the underlying call was made with the expected # request object values. @@ -2595,7 +2340,7 @@ def test_update_job_flattened_error(): @pytest.mark.asyncio async def test_update_job_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2624,7 +2369,7 @@ async def test_update_job_flattened_async(): @pytest.mark.asyncio async def test_update_job_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2669,25 +2414,6 @@ def test_delete_job(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_job_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_job), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.DeleteJobRequest() - - def test_delete_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2758,34 +2484,13 @@ def test_delete_job_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_job_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.DeleteJobRequest() - - @pytest.mark.asyncio async def test_delete_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2829,7 +2534,7 @@ async def test_delete_job_async( transport: str = "grpc_asyncio", request_type=job.DeleteJobRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2860,32 +2565,6 @@ async def test_delete_job_async_from_dict(): await test_delete_job_async(request_type=dict) -def test_delete_job_routing_parameters(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = job.DeleteJobRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_job), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_delete_job_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2927,7 +2606,7 @@ def test_delete_job_flattened_error(): @pytest.mark.asyncio async def test_delete_job_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2956,7 +2635,7 @@ async def test_delete_job_flattened_async(): @pytest.mark.asyncio async def test_delete_job_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3001,25 +2680,6 @@ def test_run_job(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_run_job_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.run_job), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.run_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.RunJobRequest() - - def test_run_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3090,34 +2750,13 @@ def test_run_job_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_run_job_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.run_job), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.run_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == job.RunJobRequest() - - @pytest.mark.asyncio async def test_run_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3161,7 +2800,7 @@ async def test_run_job_async( transport: str = "grpc_asyncio", request_type=job.RunJobRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3192,32 +2831,6 @@ async def test_run_job_async_from_dict(): await test_run_job_async(request_type=dict) -def test_run_job_routing_parameters(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = job.RunJobRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.run_job), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.run_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_run_job_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3259,7 +2872,7 @@ def test_run_job_flattened_error(): @pytest.mark.asyncio async def test_run_job_flattened_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3288,7 +2901,7 @@ async def test_run_job_flattened_async(): @pytest.mark.asyncio async def test_run_job_flattened_error_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3338,25 +2951,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3420,30 +3014,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3452,7 +3022,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3491,7 +3061,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3559,7 +3129,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3641,25 +3211,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3723,30 +3274,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3755,7 +3282,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3794,7 +3321,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3862,7 +3389,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3945,27 +3472,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -4035,31 +3541,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -4068,7 +3549,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4108,7 +3589,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4178,7 +3659,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4228,251 +3709,6 @@ def test_test_iam_permissions_from_dict_foreign(): call.assert_called() -@pytest.mark.parametrize( - "request_type", - [ - gcr_job.CreateJobRequest, - dict, - ], -) -def test_create_job_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["job"] = { - "name": "name_value", - "uid": "uid_value", - "generation": 1068, - "labels": {}, - "annotations": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "expire_time": {}, - "creator": "creator_value", - "last_modifier": "last_modifier_value", - "client": "client_value", - "client_version": "client_version_value", - "launch_stage": 6, - "binary_authorization": { - "use_default": True, - "policy": "policy_value", - "breakglass_justification": "breakglass_justification_value", - }, - "template": { - "labels": {}, - "annotations": {}, - "parallelism": 1174, - "task_count": 1083, - "template": { - "containers": [ - { - "name": "name_value", - "image": "image_value", - "command": ["command_value1", "command_value2"], - "args": ["args_value1", "args_value2"], - "env": [ - { - "name": "name_value", - "value": "value_value", - "value_source": { - "secret_key_ref": { - "secret": "secret_value", - "version": "version_value", - } - }, - } - ], - "resources": { - "limits": {}, - "cpu_idle": True, - "startup_cpu_boost": True, - }, - "ports": [{"name": "name_value", "container_port": 1511}], - "volume_mounts": [ - {"name": "name_value", "mount_path": "mount_path_value"} - ], - "working_dir": "working_dir_value", - "liveness_probe": { - "initial_delay_seconds": 2214, - "timeout_seconds": 1621, - "period_seconds": 1489, - "failure_threshold": 1812, - "http_get": { - "path": "path_value", - "http_headers": [ - {"name": "name_value", "value": "value_value"} - ], - "port": 453, - }, - "tcp_socket": {"port": 453}, - "grpc": {"port": 453, "service": "service_value"}, - }, - "startup_probe": {}, - "depends_on": ["depends_on_value1", "depends_on_value2"], - } - ], - "volumes": [ - { - "name": "name_value", - "secret": { - "secret": "secret_value", - "items": [ - { - "path": "path_value", - "version": "version_value", - "mode": 421, - } - ], - "default_mode": 1257, - }, - "cloud_sql_instance": { - "instances": ["instances_value1", "instances_value2"] - }, - "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, - "nfs": { - "server": "server_value", - "path": "path_value", - "read_only": True, - }, - "gcs": {"bucket": "bucket_value", "read_only": True}, - } - ], - "max_retries": 1187, - "timeout": {"seconds": 751, "nanos": 543}, - "service_account": "service_account_value", - "execution_environment": 1, - "encryption_key": "encryption_key_value", - "vpc_access": { - "connector": "connector_value", - "egress": 1, - "network_interfaces": [ - { - "network": "network_value", - "subnetwork": "subnetwork_value", - "tags": ["tags_value1", "tags_value2"], - } - ], - }, - }, - }, - "observed_generation": 2021, - "terminal_condition": { - "type_": "type__value", - "state": 1, - "message": "message_value", - "last_transition_time": {}, - "severity": 1, - "reason": 1, - "revision_reason": 1, - "execution_reason": 1, - }, - "conditions": {}, - "execution_count": 1628, - "latest_created_execution": { - "name": "name_value", - "create_time": {}, - "completion_time": {}, - "delete_time": {}, - "completion_status": 1, - }, - "reconciling": True, - "satisfies_pzs": True, - "start_execution_token": "start_execution_token_value", - "run_execution_token": "run_execution_token_value", - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcr_job.CreateJobRequest.meta.fields["job"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["job"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["job"][field])): - del request_init["job"][field][i][subfield] - else: - del request_init["job"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_job(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_create_job_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4626,89 +3862,10 @@ def test_create_job_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_job_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( +def test_create_job_rest_flattened(): + client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.JobsRestInterceptor, "post_create_job" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_create_job" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcr_job.CreateJobRequest.pb(gcr_job.CreateJobRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = gcr_job.CreateJobRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_job( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_job_rest_bad_request( - transport: str = "rest", request_type=gcr_job.CreateJobRequest -): - client = JobsClient( - 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.create_job(request) - - -def test_create_job_rest_flattened(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -4763,77 +3920,6 @@ def test_create_job_rest_flattened_error(transport: str = "rest"): ) -def test_create_job_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - job.GetJobRequest, - dict, - ], -) -def test_get_job_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = job.Job( - name="name_value", - uid="uid_value", - generation=1068, - creator="creator_value", - last_modifier="last_modifier_value", - client="client_value", - client_version="client_version_value", - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - observed_generation=2021, - execution_count=1628, - reconciling=True, - satisfies_pzs=True, - etag="etag_value", - start_execution_token="start_execution_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = job.Job.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_job(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, job.Job) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.generation == 1068 - assert response.creator == "creator_value" - assert response.last_modifier == "last_modifier_value" - assert response.client == "client_value" - assert response.client_version == "client_version_value" - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.observed_generation == 2021 - assert response.execution_count == 1628 - assert response.reconciling is True - assert response.satisfies_pzs is True - assert response.etag == "etag_value" - - def test_get_job_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4951,81 +4037,6 @@ def test_get_job_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_job_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(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.JobsRestInterceptor, "post_get_job" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_get_job" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = job.GetJobRequest.pb(job.GetJobRequest()) - 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 = job.Job.to_json(job.Job()) - - request = job.GetJobRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = job.Job() - - client.get_job( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_job_rest_bad_request( - transport: str = "rest", request_type=job.GetJobRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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.get_job(request) - - def test_get_job_rest_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5082,52 +4093,6 @@ def test_get_job_rest_flattened_error(transport: str = "rest"): ) -def test_get_job_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - job.ListJobsRequest, - dict, - ], -) -def test_list_jobs_rest(request_type): - client = JobsClient( - 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 = job.ListJobsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = job.ListJobsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_jobs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListJobsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_jobs_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -5262,85 +4227,10 @@ def test_list_jobs_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_jobs_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( +def test_list_jobs_rest_flattened(): + client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(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.JobsRestInterceptor, "post_list_jobs" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_list_jobs" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = job.ListJobsRequest.pb(job.ListJobsRequest()) - 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 = job.ListJobsResponse.to_json(job.ListJobsResponse()) - - request = job.ListJobsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = job.ListJobsResponse() - - client.list_jobs( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_jobs_rest_bad_request( - transport: str = "rest", request_type=job.ListJobsRequest -): - client = JobsClient( - 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.list_jobs(request) - - -def test_list_jobs_rest_flattened(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="rest", ) # Mock the http request call within the method and fake a response. @@ -5454,276 +4344,31 @@ def test_list_jobs_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - gcr_job.UpdateJobRequest, - dict, - ], -) -def test_update_job_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_update_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = {"job": {"name": "projects/sample1/locations/sample2/jobs/sample3"}} - request_init["job"] = { - "name": "projects/sample1/locations/sample2/jobs/sample3", - "uid": "uid_value", - "generation": 1068, - "labels": {}, - "annotations": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "expire_time": {}, - "creator": "creator_value", - "last_modifier": "last_modifier_value", - "client": "client_value", - "client_version": "client_version_value", - "launch_stage": 6, - "binary_authorization": { - "use_default": True, - "policy": "policy_value", - "breakglass_justification": "breakglass_justification_value", - }, - "template": { - "labels": {}, - "annotations": {}, - "parallelism": 1174, - "task_count": 1083, - "template": { - "containers": [ - { - "name": "name_value", - "image": "image_value", - "command": ["command_value1", "command_value2"], - "args": ["args_value1", "args_value2"], - "env": [ - { - "name": "name_value", - "value": "value_value", - "value_source": { - "secret_key_ref": { - "secret": "secret_value", - "version": "version_value", - } - }, - } - ], - "resources": { - "limits": {}, - "cpu_idle": True, - "startup_cpu_boost": True, - }, - "ports": [{"name": "name_value", "container_port": 1511}], - "volume_mounts": [ - {"name": "name_value", "mount_path": "mount_path_value"} - ], - "working_dir": "working_dir_value", - "liveness_probe": { - "initial_delay_seconds": 2214, - "timeout_seconds": 1621, - "period_seconds": 1489, - "failure_threshold": 1812, - "http_get": { - "path": "path_value", - "http_headers": [ - {"name": "name_value", "value": "value_value"} - ], - "port": 453, - }, - "tcp_socket": {"port": 453}, - "grpc": {"port": 453, "service": "service_value"}, - }, - "startup_probe": {}, - "depends_on": ["depends_on_value1", "depends_on_value2"], - } - ], - "volumes": [ - { - "name": "name_value", - "secret": { - "secret": "secret_value", - "items": [ - { - "path": "path_value", - "version": "version_value", - "mode": 421, - } - ], - "default_mode": 1257, - }, - "cloud_sql_instance": { - "instances": ["instances_value1", "instances_value2"] - }, - "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, - "nfs": { - "server": "server_value", - "path": "path_value", - "read_only": True, - }, - "gcs": {"bucket": "bucket_value", "read_only": True}, - } - ], - "max_retries": 1187, - "timeout": {"seconds": 751, "nanos": 543}, - "service_account": "service_account_value", - "execution_environment": 1, - "encryption_key": "encryption_key_value", - "vpc_access": { - "connector": "connector_value", - "egress": 1, - "network_interfaces": [ - { - "network": "network_value", - "subnetwork": "subnetwork_value", - "tags": ["tags_value1", "tags_value2"], - } - ], - }, - }, - }, - "observed_generation": 2021, - "terminal_condition": { - "type_": "type__value", - "state": 1, - "message": "message_value", - "last_transition_time": {}, - "severity": 1, - "reason": 1, - "revision_reason": 1, - "execution_reason": 1, - }, - "conditions": {}, - "execution_count": 1628, - "latest_created_execution": { - "name": "name_value", - "create_time": {}, - "completion_time": {}, - "delete_time": {}, - "completion_status": 1, - }, - "reconciling": True, - "satisfies_pzs": True, - "start_execution_token": "start_execution_token_value", - "run_execution_token": "run_execution_token_value", - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Determine if the message type is proto-plus or protobuf - test_field = gcr_job.UpdateJobRequest.meta.fields["job"] + # Ensure method has been cached + assert client._transport.update_job in client._transport._wrapped_methods - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_job] = mock_rpc - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["job"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["job"][field])): - del request_init["job"][field][i][subfield] - else: - del request_init["job"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_job(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_job_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_job in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_job] = mock_rpc - - request = {} - client.update_job(request) + request = {} + client.update_job(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5828,85 +4473,6 @@ def test_update_job_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_job_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.JobsRestInterceptor, "post_update_job" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_update_job" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcr_job.UpdateJobRequest.pb(gcr_job.UpdateJobRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = gcr_job.UpdateJobRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_job( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_job_rest_bad_request( - transport: str = "rest", request_type=gcr_job.UpdateJobRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"job": {"name": "projects/sample1/locations/sample2/jobs/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.update_job(request) - - def test_update_job_rest_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5963,47 +4529,6 @@ def test_update_job_rest_flattened_error(transport: str = "rest"): ) -def test_update_job_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - job.DeleteJobRequest, - dict, - ], -) -def test_delete_job_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_job(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_job_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6137,104 +4662,25 @@ def test_delete_job_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_job_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( +def test_delete_job_rest_flattened(): + client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + transport="rest", ) - client = JobsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.JobsRestInterceptor, "post_delete_job" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_delete_job" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = job.DeleteJobRequest.pb(job.DeleteJobRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) + # 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 = operations_pb2.Operation(name="operations/spam") - request = job.DeleteJobRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} - client.delete_job( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_job_rest_bad_request( - transport: str = "rest", request_type=job.DeleteJobRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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.delete_job(request) - - -def test_delete_job_rest_flattened(): - client = JobsClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/jobs/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() @@ -6270,47 +4716,6 @@ def test_delete_job_rest_flattened_error(transport: str = "rest"): ) -def test_delete_job_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - job.RunJobRequest, - dict, - ], -) -def test_run_job_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.run_job(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_run_job_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6430,85 +4835,6 @@ def test_run_job_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_job_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.JobsRestInterceptor, "post_run_job" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_run_job" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = job.RunJobRequest.pb(job.RunJobRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = job.RunJobRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.run_job( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_run_job_rest_bad_request( - transport: str = "rest", request_type=job.RunJobRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/jobs/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.run_job(request) - - def test_run_job_rest_flattened(): client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6563,52 +4889,6 @@ def test_run_job_rest_flattened_error(transport: str = "rest"): ) -def test_run_job_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.GetIamPolicyRequest, - dict, - ], -) -def test_get_iam_policy_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - def test_get_iam_policy_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -6728,139 +5008,18 @@ def test_get_iam_policy_rest_unset_required_fields(): assert set(unset_fields) == (set(("options",)) & set(("resource",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(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.JobsRestInterceptor, "post_get_iam_policy" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_get_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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.get_iam_policy(request) - - -def test_get_iam_policy_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.SetIamPolicyRequest, - dict, - ], -) -def test_set_iam_policy_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.set_iam_policy in client._transport._wrapped_methods @@ -6975,125 +5134,6 @@ def test_set_iam_policy_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), - ) - client = JobsClient(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.JobsRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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.set_iam_policy(request) - - -def test_set_iam_policy_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, - ], -) -def test_test_iam_permissions_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -7228,102 +5268,19 @@ def test_test_iam_permissions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.JobsRestTransport( +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.JobsGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.JobsRestInterceptor(), ) - client = JobsClient(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.JobsRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.JobsRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + with pytest.raises(ValueError): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/jobs/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.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_error(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.JobsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.JobsGrpcTransport( + # It is an error to provide a credentials file and a transport instance. + transport = transports.JobsGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): @@ -7403,18 +5360,2896 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = JobsClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = JobsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_job_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_job_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + call.return_value = job.Job() + client.get_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.GetJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_jobs_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + call.return_value = job.ListJobsResponse() + client.list_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.ListJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_job_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_job_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.DeleteJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_job_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.RunJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_create_job_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_job(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_job_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + call.return_value = job.Job() + client.get_job(request={"name": "projects/sample1/locations/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.GetJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_jobs_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + call.return_value = job.ListJobsResponse() + client.list_jobs(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.ListJobsRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_update_job_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_job( + request={"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest( + **{"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_job_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_job( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.DeleteJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_run_job_routing_parameters_request_1_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_job(request={"name": "projects/sample1/locations/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.RunJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_grpc_asyncio(): + transport = JobsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_job_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_job_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + execution_count=1628, + reconciling=True, + satisfies_pzs=True, + etag="etag_value", + ) + ) + await client.get_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.GetJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_jobs_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.ListJobsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.ListJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_job_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_job_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.DeleteJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_run_job_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.run_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.RunJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_job_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_job( + request={"parent": "projects/sample1/locations/sample2"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_job_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.Job( + name="name_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + execution_count=1628, + reconciling=True, + satisfies_pzs=True, + etag="etag_value", + ) + ) + await client.get_job( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.GetJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_jobs_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + job.ListJobsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_jobs(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.ListJobsRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_update_job_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_job( + request={"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest( + **{"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_job_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_job( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.DeleteJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_run_job_routing_parameters_request_1_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.run_job( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.RunJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_rest(): + transport = JobsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_job_rest_bad_request(request_type=gcr_job.CreateJobRequest): + client = JobsClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcr_job.CreateJobRequest, + dict, + ], +) +def test_create_job_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["job"] = { + "name": "name_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "policy": "policy_value", + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "labels": {}, + "annotations": {}, + "parallelism": 1174, + "task_count": 1083, + "template": { + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": { + "limits": {}, + "cpu_idle": True, + "startup_cpu_boost": True, + }, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + "working_dir": "working_dir_value", + "liveness_probe": { + "initial_delay_seconds": 2214, + "timeout_seconds": 1621, + "period_seconds": 1489, + "failure_threshold": 1812, + "http_get": { + "path": "path_value", + "http_headers": [ + {"name": "name_value", "value": "value_value"} + ], + "port": 453, + }, + "tcp_socket": {"port": 453}, + "grpc": {"port": 453, "service": "service_value"}, + }, + "startup_probe": {}, + "depends_on": ["depends_on_value1", "depends_on_value2"], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, + } + ], + "max_retries": 1187, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "vpc_access": { + "connector": "connector_value", + "egress": 1, + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "tags": ["tags_value1", "tags_value2"], + } + ], + }, + }, + }, + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "execution_count": 1628, + "latest_created_execution": { + "name": "name_value", + "create_time": {}, + "completion_time": {}, + "delete_time": {}, + "completion_status": 1, + }, + "reconciling": True, + "satisfies_pzs": True, + "start_execution_token": "start_execution_token_value", + "run_execution_token": "run_execution_token_value", + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcr_job.CreateJobRequest.meta.fields["job"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["job"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["job"][field])): + del request_init["job"][field][i][subfield] + else: + del request_init["job"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_job(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_job_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.JobsRestInterceptor, "post_create_job" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_create_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcr_job.CreateJobRequest.pb(gcr_job.CreateJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcr_job.CreateJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_job_rest_bad_request(request_type=job.GetJobRequest): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + job.GetJobRequest, + dict, + ], +) +def test_get_job_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = job.Job( + name="name_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + observed_generation=2021, + execution_count=1628, + reconciling=True, + satisfies_pzs=True, + etag="etag_value", + start_execution_token="start_execution_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = job.Job.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, job.Job) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.observed_generation == 2021 + assert response.execution_count == 1628 + assert response.reconciling is True + assert response.satisfies_pzs is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_job_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(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.JobsRestInterceptor, "post_get_job" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_get_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = job.GetJobRequest.pb(job.GetJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = job.Job.to_json(job.Job()) + req.return_value.content = return_value + + request = job.GetJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = job.Job() + + client.get_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_jobs_rest_bad_request(request_type=job.ListJobsRequest): + client = JobsClient( + 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 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_jobs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + job.ListJobsRequest, + dict, + ], +) +def test_list_jobs_rest_call_success(request_type): + client = JobsClient( + 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 = job.ListJobsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = job.ListJobsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_jobs_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(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.JobsRestInterceptor, "post_list_jobs" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_list_jobs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = job.ListJobsRequest.pb(job.ListJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = job.ListJobsResponse.to_json(job.ListJobsResponse()) + req.return_value.content = return_value + + request = job.ListJobsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = job.ListJobsResponse() + + client.list_jobs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_job_rest_bad_request(request_type=gcr_job.UpdateJobRequest): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"job": {"name": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcr_job.UpdateJobRequest, + dict, + ], +) +def test_update_job_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"job": {"name": "projects/sample1/locations/sample2/jobs/sample3"}} + request_init["job"] = { + "name": "projects/sample1/locations/sample2/jobs/sample3", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "policy": "policy_value", + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "labels": {}, + "annotations": {}, + "parallelism": 1174, + "task_count": 1083, + "template": { + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": { + "limits": {}, + "cpu_idle": True, + "startup_cpu_boost": True, + }, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + "working_dir": "working_dir_value", + "liveness_probe": { + "initial_delay_seconds": 2214, + "timeout_seconds": 1621, + "period_seconds": 1489, + "failure_threshold": 1812, + "http_get": { + "path": "path_value", + "http_headers": [ + {"name": "name_value", "value": "value_value"} + ], + "port": 453, + }, + "tcp_socket": {"port": 453}, + "grpc": {"port": 453, "service": "service_value"}, + }, + "startup_probe": {}, + "depends_on": ["depends_on_value1", "depends_on_value2"], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, + } + ], + "max_retries": 1187, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "vpc_access": { + "connector": "connector_value", + "egress": 1, + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "tags": ["tags_value1", "tags_value2"], + } + ], + }, + }, + }, + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "execution_count": 1628, + "latest_created_execution": { + "name": "name_value", + "create_time": {}, + "completion_time": {}, + "delete_time": {}, + "completion_status": 1, + }, + "reconciling": True, + "satisfies_pzs": True, + "start_execution_token": "start_execution_token_value", + "run_execution_token": "run_execution_token_value", + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcr_job.UpdateJobRequest.meta.fields["job"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["job"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["job"][field])): + del request_init["job"][field][i][subfield] + else: + del request_init["job"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_job(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_job_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.JobsRestInterceptor, "post_update_job" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_update_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcr_job.UpdateJobRequest.pb(gcr_job.UpdateJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcr_job.UpdateJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_job_rest_bad_request(request_type=job.DeleteJobRequest): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + job.DeleteJobRequest, + dict, + ], +) +def test_delete_job_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_job(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_job_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.JobsRestInterceptor, "post_delete_job" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_delete_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = job.DeleteJobRequest.pb(job.DeleteJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = job.DeleteJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_job_rest_bad_request(request_type=job.RunJobRequest): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.run_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + job.RunJobRequest, + dict, + ], +) +def test_run_job_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobs/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.run_job(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_job_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.JobsRestInterceptor, "post_run_job" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_run_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = job.RunJobRequest.pb(job.RunJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = job.RunJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.run_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(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.JobsRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(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.JobsRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest_call_success(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/jobs/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.JobsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.JobsRestInterceptor(), + ) + client = JobsClient(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.JobsRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.JobsRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_job_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + client.create_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_job_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + client.get_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.GetJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_jobs_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + client.list_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.ListJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_job_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + client.update_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_job_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + client.delete_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.DeleteJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_job_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + client.run_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = job.RunJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_create_job_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_job), "__call__") as call: + client.create_job(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.CreateJobRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_job_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_job), "__call__") as call: + client.get_job(request={"name": "projects/sample1/locations/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.GetJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_jobs_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_jobs), "__call__") as call: + client.list_jobs(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.ListJobsRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_update_job_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_job), "__call__") as call: + client.update_job( + request={"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_job.UpdateJobRequest( + **{"job": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_job_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_job), "__call__") as call: + client.delete_job( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.DeleteJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_run_job_routing_parameters_request_1_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_job), "__call__") as call: + client.run_job(request={"name": "projects/sample1/locations/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = job.RunJobRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_jobs_rest_lro_client(): + client = JobsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7660,23 +8495,6 @@ def test_jobs_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_jobs_rest_lro_client(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -8093,377 +8911,131 @@ def test_parse_secret_version_path(): } path = JobsClient.secret_version_path(**expected) - # Check that the path construction is reversible. - actual = JobsClient.parse_secret_version_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = JobsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = JobsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = JobsClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = JobsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = JobsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = JobsClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = JobsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = JobsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = JobsClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format( - project=project, - ) - actual = JobsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = JobsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = JobsClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = JobsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = JobsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = JobsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.JobsTransport, "_prep_wrapped_messages") as prep: - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.JobsTransport, "_prep_wrapped_messages") as prep: - transport_class = JobsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + # Check that the path construction is reversible. + actual = JobsClient.parse_secret_version_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + actual = JobsClient.common_billing_account_path(billing_account) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = JobsClient.common_billing_account_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + # Check that the path construction is reversible. + actual = JobsClient.parse_common_billing_account_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, ) + actual = JobsClient.common_folder_path(folder) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # 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.list_operations(request) +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = JobsClient.common_folder_path(**expected) + # Check that the path construction is reversible. + actual = JobsClient.parse_common_folder_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = JobsClient.common_organization_path(organization) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = JobsClient.common_organization_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + # Check that the path construction is reversible. + actual = JobsClient.parse_common_organization_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, ) + actual = JobsClient.common_project_path(project) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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.wait_operation(request) +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = JobsClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = JobsClient.parse_common_project_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + actual = JobsClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = JobsClient.common_location_path(**expected) - response = client.wait_operation(request) + # Check that the path construction is reversible. + actual = JobsClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.JobsTransport, "_prep_wrapped_messages") as prep: + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.JobsTransport, "_prep_wrapped_messages") as prep: + transport_class = JobsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -8493,7 +9065,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8546,7 +9118,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8591,7 +9163,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -8632,7 +9204,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8687,7 +9259,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8734,7 +9306,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -8777,7 +9349,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8832,7 +9404,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8879,7 +9451,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8922,7 +9494,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8977,7 +9549,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -9024,7 +9596,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = JobsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -9040,22 +9612,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = JobsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = JobsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = JobsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py index 04d6b89fa111..664816eae360 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import launch_stage_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -47,15 +64,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.run_v2.services.revisions import ( RevisionsAsyncClient, @@ -72,10 +81,24 @@ ) +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1164,25 +1187,6 @@ def test_get_revision(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_revision), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.GetRevisionRequest() - - def test_get_revision_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1246,44 +1250,6 @@ def test_get_revision_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_revision_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_revision), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - revision.Revision( - name="name_value", - uid="uid_value", - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - service="service_value", - max_instance_request_concurrency=3436, - service_account="service_account_value", - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, - encryption_key="encryption_key_value", - encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, - reconciling=True, - observed_generation=2021, - log_uri="log_uri_value", - satisfies_pzs=True, - session_affinity=True, - etag="etag_value", - ) - ) - response = await client.get_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.GetRevisionRequest() - - @pytest.mark.asyncio async def test_get_revision_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1292,7 +1258,7 @@ async def test_get_revision_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1331,7 +1297,7 @@ async def test_get_revision_async( transport: str = "grpc_asyncio", request_type=revision.GetRevisionRequest ): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1401,32 +1367,6 @@ async def test_get_revision_async_from_dict(): await test_get_revision_async(request_type=dict) -def test_get_revision_routing_parameters(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.GetRevisionRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_revision), "__call__") as call: - call.return_value = revision.Revision() - client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_get_revision_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1468,7 +1408,7 @@ def test_get_revision_flattened_error(): @pytest.mark.asyncio async def test_get_revision_flattened_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1495,7 +1435,7 @@ async def test_get_revision_flattened_async(): @pytest.mark.asyncio async def test_get_revision_flattened_error_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1543,25 +1483,6 @@ def test_list_revisions(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_revisions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.ListRevisionsRequest() - - def test_list_revisions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1627,29 +1548,6 @@ def test_list_revisions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_revisions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - revision.ListRevisionsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.ListRevisionsRequest() - - @pytest.mark.asyncio async def test_list_revisions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1658,7 +1556,7 @@ async def test_list_revisions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1697,7 +1595,7 @@ async def test_list_revisions_async( transport: str = "grpc_asyncio", request_type=revision.ListRevisionsRequest ): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1731,32 +1629,6 @@ async def test_list_revisions_async_from_dict(): await test_list_revisions_async(request_type=dict) -def test_list_revisions_routing_parameters(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.ListRevisionsRequest( - **{"parent": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: - call.return_value = revision.ListRevisionsResponse() - client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_list_revisions_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1798,7 +1670,7 @@ def test_list_revisions_flattened_error(): @pytest.mark.asyncio async def test_list_revisions_flattened_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1827,7 +1699,7 @@ async def test_list_revisions_flattened_async(): @pytest.mark.asyncio async def test_list_revisions_flattened_error_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1934,7 +1806,7 @@ def test_list_revisions_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_revisions_async_pager(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1984,7 +1856,7 @@ async def test_list_revisions_async_pager(): @pytest.mark.asyncio async def test_list_revisions_async_pages(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2063,25 +1935,6 @@ def test_delete_revision(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.DeleteRevisionRequest() - - def test_delete_revision_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2152,27 +2005,6 @@ def test_delete_revision_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_revision_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == revision.DeleteRevisionRequest() - - @pytest.mark.asyncio async def test_delete_revision_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2181,7 +2013,7 @@ async def test_delete_revision_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2225,7 +2057,7 @@ async def test_delete_revision_async( transport: str = "grpc_asyncio", request_type=revision.DeleteRevisionRequest ): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2256,32 +2088,6 @@ async def test_delete_revision_async_from_dict(): await test_delete_revision_async(request_type=dict) -def test_delete_revision_routing_parameters(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = revision.DeleteRevisionRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_delete_revision_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2323,7 +2129,7 @@ def test_delete_revision_flattened_error(): @pytest.mark.asyncio async def test_delete_revision_flattened_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2352,7 +2158,7 @@ async def test_delete_revision_flattened_async(): @pytest.mark.asyncio async def test_delete_revision_flattened_error_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2364,96 +2170,18 @@ async def test_delete_revision_flattened_error_async(): ) -@pytest.mark.parametrize( - "request_type", - [ - revision.GetRevisionRequest, - dict, - ], -) -def test_get_revision_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_get_revision_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" - } - 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 = revision.Revision( - name="name_value", - uid="uid_value", - generation=1068, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - service="service_value", - max_instance_request_concurrency=3436, - service_account="service_account_value", - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, - encryption_key="encryption_key_value", - encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, - reconciling=True, - observed_generation=2021, - log_uri="log_uri_value", - satisfies_pzs=True, - session_affinity=True, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = revision.Revision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, revision.Revision) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.generation == 1068 - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.service == "service_value" - assert response.max_instance_request_concurrency == 3436 - assert response.service_account == "service_account_value" - assert ( - response.execution_environment - == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1 - ) - assert response.encryption_key == "encryption_key_value" - assert ( - response.encryption_key_revocation_action - == vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW - ) - assert response.reconciling is True - assert response.observed_generation == 2021 - assert response.log_uri == "log_uri_value" - assert response.satisfies_pzs is True - assert response.session_affinity is True - assert response.etag == "etag_value" - - -def test_get_revision_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() # Ensure method has been cached assert client._transport.get_revision in client._transport._wrapped_methods @@ -2559,83 +2287,6 @@ def test_get_revision_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_revision_rest_interceptors(null_interceptor): - transport = transports.RevisionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), - ) - client = RevisionsClient(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.RevisionsRestInterceptor, "post_get_revision" - ) as post, mock.patch.object( - transports.RevisionsRestInterceptor, "pre_get_revision" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = revision.GetRevisionRequest.pb(revision.GetRevisionRequest()) - 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 = revision.Revision.to_json(revision.Revision()) - - request = revision.GetRevisionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = revision.Revision() - - client.get_revision( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_revision_rest_bad_request( - transport: str = "rest", request_type=revision.GetRevisionRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" - } - 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_revision(request) - - def test_get_revision_rest_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2695,52 +2346,6 @@ def test_get_revision_rest_flattened_error(transport: str = "rest"): ) -def test_get_revision_rest_error(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - revision.ListRevisionsRequest, - dict, - ], -) -def test_list_revisions_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/services/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 = revision.ListRevisionsResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = revision.ListRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_revisions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_revisions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2877,83 +2482,6 @@ def test_list_revisions_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_revisions_rest_interceptors(null_interceptor): - transport = transports.RevisionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), - ) - client = RevisionsClient(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.RevisionsRestInterceptor, "post_list_revisions" - ) as post, mock.patch.object( - transports.RevisionsRestInterceptor, "pre_list_revisions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = revision.ListRevisionsRequest.pb(revision.ListRevisionsRequest()) - 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 = revision.ListRevisionsResponse.to_json( - revision.ListRevisionsResponse() - ) - - request = revision.ListRevisionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = revision.ListRevisionsResponse() - - client.list_revisions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_revisions_rest_bad_request( - transport: str = "rest", request_type=revision.ListRevisionsRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/services/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.list_revisions(request) - - def test_list_revisions_rest_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3076,43 +2604,6 @@ def test_list_revisions_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - revision.DeleteRevisionRequest, - dict, - ], -) -def test_delete_revision_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" - } - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_revision(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - def test_delete_revision_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3248,87 +2739,6 @@ def test_delete_revision_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_revision_rest_interceptors(null_interceptor): - transport = transports.RevisionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), - ) - client = RevisionsClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.RevisionsRestInterceptor, "post_delete_revision" - ) as post, mock.patch.object( - transports.RevisionsRestInterceptor, "pre_delete_revision" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = revision.DeleteRevisionRequest.pb(revision.DeleteRevisionRequest()) - 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 = json_format.MessageToJson( - operations_pb2.Operation() - ) - - request = revision.DeleteRevisionRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_revision( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_revision_rest_bad_request( - transport: str = "rest", request_type=revision.DeleteRevisionRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" - } - 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.delete_revision(request) - - def test_delete_revision_rest_flattened(): client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3386,12 +2796,6 @@ def test_delete_revision_rest_flattened_error(transport: str = "rest"): ) -def test_delete_revision_rest_error(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RevisionsGrpcTransport( @@ -3484,18 +2888,1181 @@ def test_transport_adc(transport_class): adc.assert_called_once() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = RevisionsClient.get_transport_class(transport_name)( +def test_transport_kind_grpc(): + transport = RevisionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_revision_empty_call_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + call.return_value = revision.Revision() + client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.GetRevisionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_revisions_empty_call_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + call.return_value = revision.ListRevisionsResponse() + client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_revision_empty_call_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest() + + assert args[0] == request_msg + + +def test_get_revision_routing_parameters_request_1_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + call.return_value = revision.Revision() + client.get_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.GetRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_revisions_routing_parameters_request_1_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + call.return_value = revision.ListRevisionsResponse() + client.list_revisions( + request={"parent": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest( + **{"parent": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_revision_routing_parameters_request_1_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_grpc_asyncio(): + transport = RevisionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_revision_empty_call_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + revision.Revision( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service="service_value", + max_instance_request_concurrency=3436, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + reconciling=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + session_affinity=True, + etag="etag_value", + ) + ) + await client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.GetRevisionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_revisions_empty_call_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + revision.ListRevisionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_revision_empty_call_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_get_revision_routing_parameters_request_1_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + revision.Revision( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service="service_value", + max_instance_request_concurrency=3436, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + reconciling=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + session_affinity=True, + etag="etag_value", + ) + ) + await client.get_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.GetRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_revisions_routing_parameters_request_1_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + revision.ListRevisionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_revisions( + request={"parent": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest( + **{"parent": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_revision_routing_parameters_request_1_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_rest(): + transport = RevisionsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_revision_rest_bad_request(request_type=revision.GetRevisionRequest): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_revision(request) + + +@pytest.mark.parametrize( + "request_type", + [ + revision.GetRevisionRequest, + dict, + ], +) +def test_get_revision_rest_call_success(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + 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 = revision.Revision( + name="name_value", + uid="uid_value", + generation=1068, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + service="service_value", + max_instance_request_concurrency=3436, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + encryption_key="encryption_key_value", + encryption_key_revocation_action=vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW, + reconciling=True, + observed_generation=2021, + log_uri="log_uri_value", + satisfies_pzs=True, + session_affinity=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = revision.Revision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, revision.Revision) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.service == "service_value" + assert response.max_instance_request_concurrency == 3436 + assert response.service_account == "service_account_value" + assert ( + response.execution_environment + == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1 + ) + assert response.encryption_key == "encryption_key_value" + assert ( + response.encryption_key_revocation_action + == vendor_settings.EncryptionKeyRevocationAction.PREVENT_NEW + ) + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.session_affinity is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_revision_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(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.RevisionsRestInterceptor, "post_get_revision" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_get_revision" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.GetRevisionRequest.pb(revision.GetRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = revision.Revision.to_json(revision.Revision()) + req.return_value.content = return_value + + request = revision.GetRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = revision.Revision() + + client.get_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_revisions_rest_bad_request(request_type=revision.ListRevisionsRequest): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/services/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_revisions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + revision.ListRevisionsRequest, + dict, + ], +) +def test_list_revisions_rest_call_success(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/services/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 = revision.ListRevisionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = revision.ListRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_revisions_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(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.RevisionsRestInterceptor, "post_list_revisions" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_list_revisions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.ListRevisionsRequest.pb(revision.ListRevisionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = revision.ListRevisionsResponse.to_json( + revision.ListRevisionsResponse() + ) + req.return_value.content = return_value + + request = revision.ListRevisionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = revision.ListRevisionsResponse() + + client.list_revisions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_revision_rest_bad_request(request_type=revision.DeleteRevisionRequest): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.delete_revision(request) + + +@pytest.mark.parametrize( + "request_type", + [ + revision.DeleteRevisionRequest, + dict, + ], +) +def test_delete_revision_rest_call_success(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/services/sample3/revisions/sample4" + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_revision(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_revision_rest_interceptors(null_interceptor): + transport = transports.RevisionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RevisionsRestInterceptor(), + ) + client = RevisionsClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.RevisionsRestInterceptor, "post_delete_revision" + ) as post, mock.patch.object( + transports.RevisionsRestInterceptor, "pre_delete_revision" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = revision.DeleteRevisionRequest.pb(revision.DeleteRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = revision.DeleteRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_revision_empty_call_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.GetRevisionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_revisions_empty_call_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_revision_empty_call_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + client.delete_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest() + + assert args[0] == request_msg + + +def test_get_revision_routing_parameters_request_1_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_revision), "__call__") as call: + client.get_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.GetRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_revisions_routing_parameters_request_1_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_revisions), "__call__") as call: + client.list_revisions( + request={"parent": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.ListRevisionsRequest( + **{"parent": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_revision_routing_parameters_request_1_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_revision), "__call__") as call: + client.delete_revision( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = revision.DeleteRevisionRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_revisions_rest_lro_client(): + client = RevisionsClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -3735,23 +4302,6 @@ def test_revisions_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_revisions_rest_lro_client(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -4162,375 +4712,129 @@ def test_parse_service_path(): def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = RevisionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = RevisionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = RevisionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = RevisionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = RevisionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = RevisionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format( - project=project, - ) - actual = RevisionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = RevisionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = RevisionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = RevisionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RevisionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.RevisionsTransport, "_prep_wrapped_messages" - ) as prep: - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.RevisionsTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = RevisionsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RevisionsClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = RevisionsClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RevisionsClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = RevisionsClient.common_folder_path(**expected) -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_folder_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = RevisionsClient.common_organization_path(organization) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = RevisionsClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = RevisionsClient.common_project_path(project) + assert expected == actual - response = client.list_operations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = RevisionsClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_project_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = RevisionsClient.common_location_path(project, location) + assert expected == actual - # 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.wait_operation(request) +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = RevisionsClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = RevisionsClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.wait_operation(request) + with mock.patch.object( + transports.RevisionsTransport, "_prep_wrapped_messages" + ) as prep: + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + with mock.patch.object( + transports.RevisionsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RevisionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -4560,7 +4864,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4613,7 +4917,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4658,7 +4962,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -4699,7 +5003,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4754,7 +5058,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4801,7 +5105,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -4844,7 +5148,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4899,7 +5203,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4946,7 +5250,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -4989,7 +5293,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -5044,7 +5348,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -5091,7 +5395,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = RevisionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -5107,22 +5411,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = RevisionsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RevisionsAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = RevisionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py index e2de63b49bc9..428addfb79c6 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py @@ -22,10 +22,27 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api import launch_stage_pb2 # type: ignore from google.api_core import ( future, @@ -36,7 +53,7 @@ operations_v1, path_template, ) -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import operation_async # type: ignore from google.api_core import retry as retries @@ -51,16 +68,8 @@ from google.oauth2 import service_account from google.protobuf import duration_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.type import expr_pb2 # type: ignore -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.run_v2.services.services import ( ServicesAsyncClient, @@ -74,10 +83,24 @@ from google.cloud.run_v2.types import traffic_target, vendor_settings +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1116,25 +1139,6 @@ def test_create_service(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_create_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_service), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.CreateServiceRequest() - - def test_create_service_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1205,27 +1209,6 @@ def test_create_service_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_create_service_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_service), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.create_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.CreateServiceRequest() - - @pytest.mark.asyncio async def test_create_service_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1234,7 +1217,7 @@ async def test_create_service_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1278,7 +1261,7 @@ async def test_create_service_async( transport: str = "grpc_asyncio", request_type=gcr_service.CreateServiceRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1309,32 +1292,6 @@ async def test_create_service_async_from_dict(): await test_create_service_async(request_type=dict) -def test_create_service_routing_parameters(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_service.CreateServiceRequest( - **{"parent": "projects/sample1/locations/sample2"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_service), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_create_service_flattened(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1386,7 +1343,7 @@ def test_create_service_flattened_error(): @pytest.mark.asyncio async def test_create_service_flattened_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1423,7 +1380,7 @@ async def test_create_service_flattened_async(): @pytest.mark.asyncio async def test_create_service_flattened_error_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1513,25 +1470,6 @@ def test_get_service(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_service), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetServiceRequest() - - def test_get_service_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1595,49 +1533,6 @@ def test_get_service_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_service_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_service), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.Service( - name="name_value", - description="description_value", - uid="uid_value", - generation=1068, - creator="creator_value", - last_modifier="last_modifier_value", - client="client_value", - client_version="client_version_value", - ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - invoker_iam_disabled=True, - default_uri_disabled=True, - urls=["urls_value"], - custom_audiences=["custom_audiences_value"], - observed_generation=2021, - latest_ready_revision="latest_ready_revision_value", - latest_created_revision="latest_created_revision_value", - uri="uri_value", - satisfies_pzs=True, - reconciling=True, - etag="etag_value", - ) - ) - response = await client.get_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetServiceRequest() - - @pytest.mark.asyncio async def test_get_service_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -1646,7 +1541,7 @@ async def test_get_service_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1685,7 +1580,7 @@ async def test_get_service_async( transport: str = "grpc_asyncio", request_type=service.GetServiceRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1759,32 +1654,6 @@ async def test_get_service_async_from_dict(): await test_get_service_async(request_type=dict) -def test_get_service_routing_parameters(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetServiceRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_service), "__call__") as call: - call.return_value = service.Service() - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_get_service_flattened(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1826,7 +1695,7 @@ def test_get_service_flattened_error(): @pytest.mark.asyncio async def test_get_service_flattened_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1853,7 +1722,7 @@ async def test_get_service_flattened_async(): @pytest.mark.asyncio async def test_get_service_flattened_error_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1901,25 +1770,6 @@ def test_list_services(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_services_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_services), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_services() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListServicesRequest() - - def test_list_services_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1985,29 +1835,6 @@ def test_list_services_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_services_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_services), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListServicesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_services() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListServicesRequest() - - @pytest.mark.asyncio async def test_list_services_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2016,7 +1843,7 @@ async def test_list_services_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2055,7 +1882,7 @@ async def test_list_services_async( transport: str = "grpc_asyncio", request_type=service.ListServicesRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2089,32 +1916,6 @@ async def test_list_services_async_from_dict(): await test_list_services_async(request_type=dict) -def test_list_services_routing_parameters(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListServicesRequest( - **{"parent": "projects/sample1/locations/sample2"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_services), "__call__") as call: - call.return_value = service.ListServicesResponse() - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_list_services_flattened(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2156,7 +1957,7 @@ def test_list_services_flattened_error(): @pytest.mark.asyncio async def test_list_services_flattened_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2185,7 +1986,7 @@ async def test_list_services_flattened_async(): @pytest.mark.asyncio async def test_list_services_flattened_error_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2292,7 +2093,7 @@ def test_list_services_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_services_async_pager(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2342,7 +2143,7 @@ async def test_list_services_async_pager(): @pytest.mark.asyncio async def test_list_services_async_pages(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2421,25 +2222,6 @@ def test_update_service(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_update_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_service), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.update_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.UpdateServiceRequest() - - def test_update_service_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2504,27 +2286,6 @@ def test_update_service_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_update_service_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_service), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.update_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcr_service.UpdateServiceRequest() - - @pytest.mark.asyncio async def test_update_service_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2533,7 +2294,7 @@ async def test_update_service_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2577,7 +2338,7 @@ async def test_update_service_async( transport: str = "grpc_asyncio", request_type=gcr_service.UpdateServiceRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2608,33 +2369,7 @@ async def test_update_service_async_from_dict(): await test_update_service_async(request_type=dict) -def test_update_service_routing_parameters(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcr_service.UpdateServiceRequest( - **{"service": {"name": "projects/sample1/locations/sample2/sample3"}} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_service), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - -def test_update_service_flattened(): +def test_update_service_flattened(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2680,7 +2415,7 @@ def test_update_service_flattened_error(): @pytest.mark.asyncio async def test_update_service_flattened_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2713,7 +2448,7 @@ async def test_update_service_flattened_async(): @pytest.mark.asyncio async def test_update_service_flattened_error_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -2759,25 +2494,6 @@ def test_delete_service(request_type, transport: str = "grpc"): assert isinstance(response, future.Future) -def test_delete_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_service), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.delete_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteServiceRequest() - - def test_delete_service_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -2848,27 +2564,6 @@ def test_delete_service_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_delete_service_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_service), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - response = await client.delete_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteServiceRequest() - - @pytest.mark.asyncio async def test_delete_service_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -2877,7 +2572,7 @@ async def test_delete_service_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2921,7 +2616,7 @@ async def test_delete_service_async( transport: str = "grpc_asyncio", request_type=service.DeleteServiceRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -2952,32 +2647,6 @@ async def test_delete_service_async_from_dict(): await test_delete_service_async(request_type=dict) -def test_delete_service_routing_parameters(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteServiceRequest( - **{"name": "projects/sample1/locations/sample2/sample3"} - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_service), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - def test_delete_service_flattened(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3019,7 +2688,7 @@ def test_delete_service_flattened_error(): @pytest.mark.asyncio async def test_delete_service_flattened_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3048,7 +2717,7 @@ async def test_delete_service_flattened_async(): @pytest.mark.asyncio async def test_delete_service_flattened_error_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -3098,25 +2767,6 @@ def test_get_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - def test_get_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3180,30 +2830,6 @@ def test_get_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - @pytest.mark.asyncio async def test_get_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3212,7 +2838,7 @@ async def test_get_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3251,7 +2877,7 @@ async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3319,7 +2945,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3401,25 +3027,6 @@ def test_set_iam_policy(request_type, transport: str = "grpc"): assert response.etag == b"etag_blob" -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - def test_set_iam_policy_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3483,30 +3090,6 @@ def test_set_iam_policy_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_set_iam_policy_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - response = await client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - @pytest.mark.asyncio async def test_set_iam_policy_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3515,7 +3098,7 @@ async def test_set_iam_policy_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3554,7 +3137,7 @@ async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3622,7 +3205,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3705,27 +3288,6 @@ def test_test_iam_permissions(request_type, transport: str = "grpc"): assert response.permissions == ["permissions_value"] -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -3795,31 +3357,6 @@ def test_test_iam_permissions_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - response = await client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - @pytest.mark.asyncio async def test_test_iam_permissions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", @@ -3828,7 +3365,7 @@ async def test_test_iam_permissions_async_use_cached_wrapped_rpc( # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3868,7 +3405,7 @@ async def test_test_iam_permissions_async( request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3938,7 +3475,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3988,828 +3525,2258 @@ def test_test_iam_permissions_from_dict_foreign(): call.assert_called() -@pytest.mark.parametrize( - "request_type", - [ - gcr_service.CreateServiceRequest, - dict, - ], -) -def test_create_service_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_create_service_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_service] = mock_rpc + + request = {} + client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_service_rest_required_fields( + request_type=gcr_service.CreateServiceRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["service_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["service"] = { - "name": "name_value", - "description": "description_value", - "uid": "uid_value", - "generation": 1068, - "labels": {}, - "annotations": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "expire_time": {}, - "creator": "creator_value", - "last_modifier": "last_modifier_value", - "client": "client_value", - "client_version": "client_version_value", - "ingress": 1, - "launch_stage": 6, - "binary_authorization": { - "use_default": True, - "policy": "policy_value", - "breakglass_justification": "breakglass_justification_value", - }, - "template": { - "revision": "revision_value", - "labels": {}, - "annotations": {}, - "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, - "vpc_access": { - "connector": "connector_value", - "egress": 1, - "network_interfaces": [ - { - "network": "network_value", - "subnetwork": "subnetwork_value", - "tags": ["tags_value1", "tags_value2"], - } + # verify fields with default values are dropped + assert "serviceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == request_init["service_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["serviceId"] = "service_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "service_id", + "validate_only", + ) + ) + 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" + assert "serviceId" in jsonified_request + assert jsonified_request["serviceId"] == "service_id_value" + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_service(request) + + expected_params = [ + ( + "serviceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "serviceId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "service", + "serviceId", + ) + ) + ) + + +def test_create_service_rest_flattened(): + client = ServicesClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # 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", + service=gcr_service.Service(name="name_value"), + service_id="service_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_service(**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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, + args[1], + ) + + +def test_create_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + gcr_service.CreateServiceRequest(), + parent="parent_value", + service=gcr_service.Service(name="name_value"), + service_id="service_id_value", + ) + + +def test_get_service_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_service] = mock_rpc + + request = {} + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_service_rest_required_fields(request_type=service.GetServiceRequest): + transport_class = transports.ServicesRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_service._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_service._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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Service() + # 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 + + # Convert return value to protobuf type + return_value = service.Service.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_service(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_service_rest_flattened(): + client = ServicesClient( + 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 = service.Service() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/services/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 + # Convert return value to protobuf type + return_value = service.Service.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_service(**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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, + args[1], + ) + + +def test_get_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + service.GetServiceRequest(), + name="name_value", + ) + + +def test_list_services_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_services in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_services] = mock_rpc + + request = {} + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_services(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_services_rest_required_fields(request_type=service.ListServicesRequest): + transport_class = transports.ServicesRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_services._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() + ).list_services._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "show_deleted", + ) + ) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListServicesResponse() + # 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 + + # Convert return value to protobuf type + return_value = service.ListServicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_services(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_services_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_services._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_services_rest_flattened(): + client = ServicesClient( + 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 = service.ListServicesResponse() + + # 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", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListServicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_services(**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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, + args[1], + ) + + +def test_list_services_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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.list_services( + service.ListServicesRequest(), + parent="parent_value", + ) + + +def test_list_services_rest_pager(transport: str = "rest"): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), ], - }, - "timeout": {"seconds": 751, "nanos": 543}, - "service_account": "service_account_value", - "containers": [ - { - "name": "name_value", - "image": "image_value", - "command": ["command_value1", "command_value2"], - "args": ["args_value1", "args_value2"], - "env": [ - { - "name": "name_value", - "value": "value_value", - "value_source": { - "secret_key_ref": { - "secret": "secret_value", - "version": "version_value", - } - }, - } - ], - "resources": { - "limits": {}, - "cpu_idle": True, - "startup_cpu_boost": True, - }, - "ports": [{"name": "name_value", "container_port": 1511}], - "volume_mounts": [ - {"name": "name_value", "mount_path": "mount_path_value"} - ], - "working_dir": "working_dir_value", - "liveness_probe": { - "initial_delay_seconds": 2214, - "timeout_seconds": 1621, - "period_seconds": 1489, - "failure_threshold": 1812, - "http_get": { - "path": "path_value", - "http_headers": [ - {"name": "name_value", "value": "value_value"} - ], - "port": 453, - }, - "tcp_socket": {"port": 453}, - "grpc": {"port": 453, "service": "service_value"}, - }, - "startup_probe": {}, - "depends_on": ["depends_on_value1", "depends_on_value2"], - } - ], - "volumes": [ - { - "name": "name_value", - "secret": { - "secret": "secret_value", - "items": [ - { - "path": "path_value", - "version": "version_value", - "mode": 421, - } - ], - "default_mode": 1257, - }, - "cloud_sql_instance": { - "instances": ["instances_value1", "instances_value2"] - }, - "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, - "nfs": { - "server": "server_value", - "path": "path_value", - "read_only": True, - }, - "gcs": {"bucket": "bucket_value", "read_only": True}, - } - ], - "execution_environment": 1, - "encryption_key": "encryption_key_value", - "max_instance_request_concurrency": 3436, - "service_mesh": {"mesh": "mesh_value"}, - "session_affinity": True, - "health_check_disabled": True, - "node_selector": {"accelerator": "accelerator_value"}, - }, - "traffic": [ - { - "type_": 1, - "revision": "revision_value", - "percent": 753, - "tag": "tag_value", + next_page_token="abc", + ), + service.ListServicesResponse( + services=[], + next_page_token="def", + ), + service.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token="ghi", + ), + service.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListServicesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.Service) for i in results) + + pages = list(client.list_services(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_service_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_service] = mock_rpc + + request = {} + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_service_rest_required_fields( + request_type=gcr_service.UpdateServiceRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_service._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_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "update_mask", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_service(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + "validateOnly", + ) + ) + & set(("service",)) + ) + + +def test_update_service_rest_flattened(): + client = ServicesClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "service": {"name": "projects/sample1/locations/sample2/services/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + service=gcr_service.Service(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_service(**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/v2/{service.name=projects/*/locations/*/services/*}" + % client.transport._host, + args[1], + ) + + +def test_update_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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_service( + gcr_service.UpdateServiceRequest(), + service=gcr_service.Service(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_service_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_service] = mock_rpc + + request = {} + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_service_rest_required_fields(request_type=service.DeleteServiceRequest): + transport_class = transports.ServicesRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_service._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() + ).delete_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "validate_only", + ) + ) + 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 = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_service(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_service_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +def test_delete_service_rest_flattened(): + client = ServicesClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/services/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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_service(**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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, + args[1], + ) + + +def test_delete_service_rest_flattened_error(transport: str = "rest"): + client = ServicesClient( + 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.delete_service( + service.DeleteServiceRequest(), + name="name_value", + ) + + +def test_get_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc + + request = {} + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } - ], - "scaling": {"min_instance_count": 1920, "scaling_mode": 1}, - "invoker_iam_disabled": True, - "default_uri_disabled": True, - "urls": ["urls_value1", "urls_value2"], - "custom_audiences": ["custom_audiences_value1", "custom_audiences_value2"], - "observed_generation": 2021, - "terminal_condition": { - "type_": "type__value", - "state": 1, - "message": "message_value", - "last_transition_time": {}, - "severity": 1, - "reason": 1, - "revision_reason": 1, - "execution_reason": 1, - }, - "conditions": {}, - "latest_ready_revision": "latest_ready_revision_value", - "latest_created_revision": "latest_created_revision_value", - "traffic_statuses": [ - { - "type_": 1, - "revision": "revision_value", - "percent": 753, - "tag": "tag_value", - "uri": "uri_value", + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("options",)) & set(("resource",))) + + +def test_set_iam_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_iam_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc + + request = {} + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_iam_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - ], - "uri": "uri_value", - "satisfies_pzs": True, - "reconciling": True, - "etag": "etag_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "policy", + ) + ) + ) + + +def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.test_iam_permissions in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.test_iam_permissions + ] = mock_rpc + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.ServicesRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # 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 + 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 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServicesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServicesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServicesClient(transport=transport) + assert client.transport is transport - # Determine if the message type is proto-plus or protobuf - test_field = gcr_service.CreateServiceRequest.meta.fields["service"] - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + transport = transports.ServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, + transports.ServicesRestTransport, + ], +) +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() - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["service"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_transport_kind_grpc(): + transport = ServicesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["service"][field])): - del request_init["service"][field][i][subfield] - else: - del request_init["service"][field][subfield] - request = request_type(**request_init) +def test_initialize_client_w_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None - # 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 = operations_pb2.Operation(name="operations/spam") - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_service_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_service(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_service(request=None) - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest() + assert args[0] == request_msg -def test_create_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_service_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Ensure method has been cached - assert client._transport.create_service in client._transport._wrapped_methods + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + call.return_value = service.Service() + client.get_service(request=None) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_service] = mock_rpc + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetServiceRequest() - request = {} - client.create_service(request) + assert args[0] == request_msg - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_services_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - client.create_service(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + call.return_value = service.ListServicesResponse() + client.list_services(request=None) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListServicesRequest() + assert args[0] == request_msg -def test_create_service_rest_required_fields( - request_type=gcr_service.CreateServiceRequest, -): - transport_class = transports.ServicesRestTransport - request_init = {} - request_init["parent"] = "" - request_init["service_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_service_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # verify fields with default values are dropped - assert "serviceId" not in jsonified_request + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_service_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteServiceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + + assert args[0] == request_msg + + +def test_create_service_routing_parameters_request_1_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_service(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_service_routing_parameters_request_1_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + call.return_value = service.Service() + client.get_service( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) - # verify required fields with default values are now present - assert "serviceId" in jsonified_request - assert jsonified_request["serviceId"] == request_init["service_id"] + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.GetServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) - jsonified_request["parent"] = "parent_value" - jsonified_request["serviceId"] = "service_id_value" + assert args[0] == request_msg - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_service._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "service_id", - "validate_only", + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) - ) - 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" - assert "serviceId" in jsonified_request - assert jsonified_request["serviceId"] == "service_id_value" +def test_list_services_routing_parameters_request_1_grpc(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + call.return_value = service.ListServicesResponse() + client.list_services(request={"parent": "projects/sample1/locations/sample2"}) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.ListServicesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) - response = client.create_service(request) + assert args[0] == request_msg - expected_params = [ - ( - "serviceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) -def test_create_service_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_update_service_routing_parameters_request_1_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - unset_fields = transport.create_service._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "serviceId", - "validateOnly", - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_service( + request={"service": {"name": "projects/sample1/locations/sample2/sample3"}} ) - & set( - ( - "parent", - "service", - "serviceId", - ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest( + **{"service": {"name": "projects/sample1/locations/sample2/sample3"}} ) - ) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_service_rest_interceptors(null_interceptor): - transport = transports.ServicesRestTransport( + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_service_routing_parameters_request_1_grpc(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + transport="grpc", ) - client = ServicesClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.ServicesRestInterceptor, "post_create_service" - ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_create_service" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = gcr_service.CreateServiceRequest.pb( - gcr_service.CreateServiceRequest() + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_service( + request={"name": "projects/sample1/locations/sample2/sample3"} ) - 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 = json_format.MessageToJson( - operations_pb2.Operation() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.DeleteServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} ) - request = gcr_service.CreateServiceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + assert args[0] == request_msg - client.create_service( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) - pre.assert_called_once() - post.assert_called_once() - -def test_create_service_rest_bad_request( - transport: str = "rest", request_type=gcr_service.CreateServiceRequest -): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_transport_kind_grpc_asyncio(): + transport = ServicesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() ) + assert transport.kind == "grpc_asyncio" - # 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.create_service(request) +def test_initialize_client_w_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None -def test_create_service_rest_flattened(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_service_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # 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 = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_service(request=None) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - service=gcr_service.Service(name="name_value"), - service_id="service_id_value", + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_service_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.Service( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + invoker_iam_disabled=True, + default_uri_disabled=True, + urls=["urls_value"], + custom_audiences=["custom_audiences_value"], + observed_generation=2021, + latest_ready_revision="latest_ready_revision_value", + latest_created_revision="latest_created_revision_value", + uri="uri_value", + satisfies_pzs=True, + reconciling=True, + etag="etag_value", + ) ) - mock_args.update(sample_request) + await client.get_service(request=None) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetServiceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_services_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_services(request=None) - client.create_service(**mock_args) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListServicesRequest() - # 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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, - args[1], - ) + assert args[0] == request_msg -def test_create_service_rest_flattened_error(transport: str = "rest"): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_service_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_service( - gcr_service.CreateServiceRequest(), - parent="parent_value", - service=gcr_service.Service(name="name_value"), - service_id="service_id_value", + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.update_service(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest() -def test_create_service_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - service.GetServiceRequest, - dict, - ], -) -def test_get_service_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_service_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/services/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 = service.Service( - name="name_value", - description="description_value", - uid="uid_value", - generation=1068, - creator="creator_value", - last_modifier="last_modifier_value", - client="client_value", - client_version="client_version_value", - ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, - launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, - invoker_iam_disabled=True, - default_uri_disabled=True, - urls=["urls_value"], - custom_audiences=["custom_audiences_value"], - observed_generation=2021, - latest_ready_revision="latest_ready_revision_value", - latest_created_revision="latest_created_revision_value", - uri="uri_value", - satisfies_pzs=True, - reconciling=True, - etag="etag_value", + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + await client.delete_service(request=None) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.Service.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteServiceRequest() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_service(request) + assert args[0] == request_msg - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.uid == "uid_value" - assert response.generation == 1068 - assert response.creator == "creator_value" - assert response.last_modifier == "last_modifier_value" - assert response.client == "client_value" - assert response.client_version == "client_version_value" - assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL - assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED - assert response.invoker_iam_disabled is True - assert response.default_uri_disabled is True - assert response.urls == ["urls_value"] - assert response.custom_audiences == ["custom_audiences_value"] - assert response.observed_generation == 2021 - assert response.latest_ready_revision == "latest_ready_revision_value" - assert response.latest_created_revision == "latest_created_revision_value" - assert response.uri == "uri_value" - assert response.satisfies_pzs is True - assert response.reconciling is True - assert response.etag == "etag_value" +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) -def test_get_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) + await client.get_iam_policy(request=None) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() - # Ensure method has been cached - assert client._transport.get_service in client._transport._wrapped_methods + assert args[0] == request_msg - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) - client._transport._wrapped_methods[client._transport.get_service] = mock_rpc + await client.set_iam_policy(request=None) - request = {} - client.get_service(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert args[0] == request_msg - client.get_service(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() -def test_get_service_rest_required_fields(request_type=service.GetServiceRequest): - transport_class = transports.ServicesRestTransport + assert args[0] == request_msg - 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, use_integers_for_enums=False) + +@pytest.mark.asyncio +async def test_create_service_routing_parameters_request_1_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - # verify fields with default values are dropped + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_service( + request={"parent": "projects/sample1/locations/sample2"} + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) - # verify required fields with default values are now present + assert args[0] == request_msg - jsonified_request["name"] = "name_value" + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_service._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" +@pytest.mark.asyncio +async def test_get_service_routing_parameters_request_1_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.Service( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + invoker_iam_disabled=True, + default_uri_disabled=True, + urls=["urls_value"], + custom_audiences=["custom_audiences_value"], + observed_generation=2021, + latest_ready_revision="latest_ready_revision_value", + latest_created_revision="latest_created_revision_value", + uri="uri_value", + satisfies_pzs=True, + reconciling=True, + etag="etag_value", + ) + ) + await client.get_service( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.GetServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + + assert args[0] == request_msg - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) - # Designate an appropriate value for the returned response. - return_value = service.Service() - # 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 +@pytest.mark.asyncio +async def test_list_services_routing_parameters_request_1_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) - # Convert return value to protobuf type - return_value = service.Service.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_services( + request={"parent": "projects/sample1/locations/sample2"} + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.ListServicesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) - response = client.get_service(request) + assert args[0] == request_msg - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) -def test_get_service_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_update_service_routing_parameters_request_1_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - unset_fields = transport.get_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_service( + request={"service": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest( + **{"service": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_service_rest_interceptors(null_interceptor): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_service_routing_parameters_request_1_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", ) - client = ServicesClient(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.ServicesRestInterceptor, "post_get_service" - ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_get_service" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetServiceRequest.pb(service.GetServiceRequest()) - 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 = service.Service.to_json(service.Service()) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_service( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) - request = service.GetServiceRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.Service() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.DeleteServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) - client.get_service( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) - pre.assert_called_once() - post.assert_called_once() + +def test_transport_kind_rest(): + transport = ServicesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" -def test_get_service_rest_bad_request( - transport: str = "rest", request_type=service.GetServiceRequest -): +def test_create_service_rest_bad_request(request_type=gcr_service.CreateServiceRequest): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/services/sample3"} + 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. @@ -4817,268 +5784,454 @@ def test_get_service_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_service(request) + client.create_service(request) -def test_get_service_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + gcr_service.CreateServiceRequest, + dict, + ], +) +def test_create_service_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = service.Service() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/services/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 - # Convert return value to protobuf type - return_value = service.Service.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_service(**mock_args) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["service"] = { + "name": "name_value", + "description": "description_value", + "uid": "uid_value", + "generation": 1068, + "labels": {}, + "annotations": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "creator": "creator_value", + "last_modifier": "last_modifier_value", + "client": "client_value", + "client_version": "client_version_value", + "ingress": 1, + "launch_stage": 6, + "binary_authorization": { + "use_default": True, + "policy": "policy_value", + "breakglass_justification": "breakglass_justification_value", + }, + "template": { + "revision": "revision_value", + "labels": {}, + "annotations": {}, + "scaling": {"min_instance_count": 1920, "max_instance_count": 1922}, + "vpc_access": { + "connector": "connector_value", + "egress": 1, + "network_interfaces": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "tags": ["tags_value1", "tags_value2"], + } + ], + }, + "timeout": {"seconds": 751, "nanos": 543}, + "service_account": "service_account_value", + "containers": [ + { + "name": "name_value", + "image": "image_value", + "command": ["command_value1", "command_value2"], + "args": ["args_value1", "args_value2"], + "env": [ + { + "name": "name_value", + "value": "value_value", + "value_source": { + "secret_key_ref": { + "secret": "secret_value", + "version": "version_value", + } + }, + } + ], + "resources": { + "limits": {}, + "cpu_idle": True, + "startup_cpu_boost": True, + }, + "ports": [{"name": "name_value", "container_port": 1511}], + "volume_mounts": [ + {"name": "name_value", "mount_path": "mount_path_value"} + ], + "working_dir": "working_dir_value", + "liveness_probe": { + "initial_delay_seconds": 2214, + "timeout_seconds": 1621, + "period_seconds": 1489, + "failure_threshold": 1812, + "http_get": { + "path": "path_value", + "http_headers": [ + {"name": "name_value", "value": "value_value"} + ], + "port": 453, + }, + "tcp_socket": {"port": 453}, + "grpc": {"port": 453, "service": "service_value"}, + }, + "startup_probe": {}, + "depends_on": ["depends_on_value1", "depends_on_value2"], + } + ], + "volumes": [ + { + "name": "name_value", + "secret": { + "secret": "secret_value", + "items": [ + { + "path": "path_value", + "version": "version_value", + "mode": 421, + } + ], + "default_mode": 1257, + }, + "cloud_sql_instance": { + "instances": ["instances_value1", "instances_value2"] + }, + "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, + } + ], + "execution_environment": 1, + "encryption_key": "encryption_key_value", + "max_instance_request_concurrency": 3436, + "service_mesh": {"mesh": "mesh_value"}, + "session_affinity": True, + "health_check_disabled": True, + "node_selector": {"accelerator": "accelerator_value"}, + }, + "traffic": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + } + ], + "scaling": {"min_instance_count": 1920, "scaling_mode": 1}, + "invoker_iam_disabled": True, + "default_uri_disabled": True, + "urls": ["urls_value1", "urls_value2"], + "custom_audiences": ["custom_audiences_value1", "custom_audiences_value2"], + "observed_generation": 2021, + "terminal_condition": { + "type_": "type__value", + "state": 1, + "message": "message_value", + "last_transition_time": {}, + "severity": 1, + "reason": 1, + "revision_reason": 1, + "execution_reason": 1, + }, + "conditions": {}, + "latest_ready_revision": "latest_ready_revision_value", + "latest_created_revision": "latest_created_revision_value", + "traffic_statuses": [ + { + "type_": 1, + "revision": "revision_value", + "percent": 753, + "tag": "tag_value", + "uri": "uri_value", + } + ], + "uri": "uri_value", + "satisfies_pzs": True, + "reconciling": True, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # 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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, - args[1], - ) + # Determine if the message type is proto-plus or protobuf + test_field = gcr_service.CreateServiceRequest.meta.fields["service"] + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] -def test_get_service_rest_flattened_error(transport: str = "rest"): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_service( - service.GetServiceRequest(), - name="name_value", - ) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -def test_get_service_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["service"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - service.ListServicesRequest, - dict, - ], -) -def test_list_services_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["service"][field])): + del request_init["service"][field][i][subfield] + else: + del request_init["service"][field][subfield] 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 = service.ListServicesResponse( - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListServicesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_services(request) + response = client.create_service(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_services_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_services in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.list_services] = mock_rpc - - request = {} - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_services(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - + json_return_value = json_format.MessageToJson(return_value) -def test_list_services_rest_required_fields(request_type=service.ListServicesRequest): - transport_class = transports.ServicesRestTransport - 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, use_integers_for_enums=False) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_service_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) + client = ServicesClient(transport=transport) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_services._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ServicesRestInterceptor, "post_create_service" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_create_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcr_service.CreateServiceRequest.pb( + gcr_service.CreateServiceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # verify required fields with default values are now present + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value - jsonified_request["parent"] = "parent_value" + request = gcr_service.CreateServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_services._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - "show_deleted", + client.create_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - ) - 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" + pre.assert_called_once() + post.assert_called_once() + +def test_get_service_rest_bad_request(request_type=service.GetServiceRequest): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = service.ListServicesResponse() - # 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 + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_service(request) - # Convert return value to protobuf type - return_value = service.ListServicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + service.GetServiceRequest, + dict, + ], +) +def test_get_service_rest_call_success(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.list_services(request) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/sample3"} + request = request_type(**request_init) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # 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 = service.Service( + name="name_value", + description="description_value", + uid="uid_value", + generation=1068, + creator="creator_value", + last_modifier="last_modifier_value", + client="client_value", + client_version="client_version_value", + ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, + launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + invoker_iam_disabled=True, + default_uri_disabled=True, + urls=["urls_value"], + custom_audiences=["custom_audiences_value"], + observed_generation=2021, + latest_ready_revision="latest_ready_revision_value", + latest_created_revision="latest_created_revision_value", + uri="uri_value", + satisfies_pzs=True, + reconciling=True, + etag="etag_value", + ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 -def test_list_services_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Convert return value to protobuf type + return_value = service.Service.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_service(request) - unset_fields = transport.list_services._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - "showDeleted", - ) - ) - & set(("parent",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.creator == "creator_value" + assert response.last_modifier == "last_modifier_value" + assert response.client == "client_value" + assert response.client_version == "client_version_value" + assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL + assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.invoker_iam_disabled is True + assert response.default_uri_disabled is True + assert response.urls == ["urls_value"] + assert response.custom_audiences == ["custom_audiences_value"] + assert response.observed_generation == 2021 + assert response.latest_ready_revision == "latest_ready_revision_value" + assert response.latest_created_revision == "latest_created_revision_value" + assert response.uri == "uri_value" + assert response.satisfies_pzs is True + assert response.reconciling is True + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_services_rest_interceptors(null_interceptor): +def test_get_service_rest_interceptors(null_interceptor): transport = transports.ServicesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) client = ServicesClient(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.ServicesRestInterceptor, "post_list_services" + transports.ServicesRestInterceptor, "post_get_service" ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_list_services" + transports.ServicesRestInterceptor, "pre_get_service" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListServicesRequest.pb(service.ListServicesRequest()) + pb_message = service.GetServiceRequest.pb(service.GetServiceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -5086,22 +6239,20 @@ def test_list_services_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = service.ListServicesResponse.to_json( - service.ListServicesResponse() - ) + return_value = service.Service.to_json(service.Service()) + req.return_value.content = return_value - request = service.ListServicesRequest() + request = service.GetServiceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListServicesResponse() + post.return_value = service.Service() - client.list_services( + client.get_service( request, metadata=[ ("key", "val"), @@ -5113,14 +6264,10 @@ def test_list_services_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_services_rest_bad_request( - transport: str = "rest", request_type=service.ListServicesRequest -): +def test_list_services_rest_bad_request(request_type=service.ListServicesRequest): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + 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) @@ -5130,128 +6277,130 @@ def test_list_services_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value client.list_services(request) -def test_list_services_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.ListServicesRequest, + dict, + ], +) +def test_list_services_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = service.ListServicesResponse() - - # 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", + return_value = service.ListServicesResponse( + next_page_token="next_page_token_value", ) - mock_args.update(sample_request) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 + # Convert return value to protobuf type return_value = service.ListServicesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.list_services(request) - client.list_services(**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/v2/{parent=projects/*/locations/*}/services" % client.transport._host, - args[1], - ) - - -def test_list_services_rest_flattened_error(transport: str = "rest"): - client = ServicesClient( - 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.list_services( - service.ListServicesRequest(), - parent="parent_value", - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == "next_page_token_value" -def test_list_services_rest_pager(transport: str = "rest"): - client = ServicesClient( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_services_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) + client = ServicesClient(transport=transport) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token="abc", - ), - service.ListServicesResponse( - services=[], - next_page_token="def", - ), - service.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token="ghi", - ), - service.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServicesRestInterceptor, "post_list_services" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_list_services" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListServicesRequest.pb(service.ListServicesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListServicesResponse.to_json( + service.ListServicesResponse() ) - # Two responses for two calls - response = response + response + req.return_value.content = return_value - # Wrap the values into proper Response objs - response = tuple(service.ListServicesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + request = service.ListServicesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListServicesResponse() - sample_request = {"parent": "projects/sample1/locations/sample2"} + client.list_services( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - pager = client.list_services(request=sample_request) + pre.assert_called_once() + post.assert_called_once() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service.Service) for i in results) - pages = list(client.list_services(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_update_service_rest_bad_request(request_type=gcr_service.UpdateServiceRequest): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "service": {"name": "projects/sample1/locations/sample2/services/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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_service(request) @pytest.mark.parametrize( @@ -5261,10 +6410,9 @@ def test_list_services_rest_pager(transport: str = "rest"): dict, ], ) -def test_update_service_rest(request_type): +def test_update_service_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -5488,169 +6636,35 @@ def get_message_fields(field): } ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["service"][field])): - del request_init["service"][field][i][subfield] - else: - del request_init["service"][field][subfield] - 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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_service(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.update_service] = mock_rpc - - request = {} - client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_service_rest_required_fields( - request_type=gcr_service.UpdateServiceRequest, -): - transport_class = transports.ServicesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_service._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_service._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "update_mask", - "validate_only", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.update_service(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["service"][field])): + del request_init["service"][field][i][subfield] + else: + del request_init["service"][field][subfield] + 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 = operations_pb2.Operation(name="operations/spam") -def test_update_service_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_service(request) - unset_fields = transport.update_service._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "updateMask", - "validateOnly", - ) - ) - & set(("service",)) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5660,6 +6674,7 @@ def test_update_service_rest_interceptors(null_interceptor): interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) client = ServicesClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5683,12 +6698,10 @@ def test_update_service_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = gcr_service.UpdateServiceRequest() metadata = [ @@ -5710,18 +6723,12 @@ def test_update_service_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_service_rest_bad_request( - transport: str = "rest", request_type=gcr_service.UpdateServiceRequest -): +def test_delete_service_rest_bad_request(request_type=service.DeleteServiceRequest): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = { - "service": {"name": "projects/sample1/locations/sample2/services/sample3"} - } + request_init = {"name": "projects/sample1/locations/sample2/services/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5729,76 +6736,13 @@ def test_update_service_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_service(request) - - -def test_update_service_rest_flattened(): - client = ServicesClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "service": {"name": "projects/sample1/locations/sample2/services/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - service=gcr_service.Service(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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.update_service(**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/v2/{service.name=projects/*/locations/*/services/*}" - % client.transport._host, - args[1], - ) - - -def test_update_service_rest_flattened_error(transport: str = "rest"): - client = ServicesClient( - 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_service( - gcr_service.UpdateServiceRequest(), - service=gcr_service.Service(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_update_service_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.delete_service(request) @pytest.mark.parametrize( @@ -5808,165 +6752,30 @@ def test_update_service_rest_error(): dict, ], ) -def test_delete_service_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/services/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 = operations_pb2.Operation(name="operations/spam") - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.delete_service(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.delete_service] = mock_rpc - - request = {} - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_service_rest_required_fields(request_type=service.DeleteServiceRequest): - transport_class = transports.ServicesRestTransport - - 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, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_service._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() - ).delete_service._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "validate_only", - ) - ) - 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" - +def test_delete_service_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # 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": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_service(request) + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/services/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 = operations_pb2.Operation(name="operations/spam") -def test_delete_service_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_service(request) - unset_fields = transport.delete_service._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "validateOnly", - ) - ) - & set(("name",)) - ) + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5976,6 +6785,7 @@ def test_delete_service_rest_interceptors(null_interceptor): interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) client = ServicesClient(transport=transport) + with mock.patch.object( type(client.transport._session), "request" ) as req, mock.patch.object( @@ -5997,12 +6807,10 @@ def test_delete_service_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value request = service.DeleteServiceRequest() metadata = [ @@ -6024,16 +6832,14 @@ def test_delete_service_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_service_rest_bad_request( - transport: str = "rest", request_type=service.DeleteServiceRequest +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/services/sample3"} + request_init = {"resource": "projects/sample1/locations/sample2/services/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6041,71 +6847,13 @@ def test_delete_service_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_service(request) - - -def test_delete_service_rest_flattened(): - client = ServicesClient( - 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 = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/services/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 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value.request = mock.Mock() req.return_value = response_value - - client.delete_service(**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/v2/{name=projects/*/locations/*/services/*}" % client.transport._host, - args[1], - ) - - -def test_delete_service_rest_flattened_error(transport: str = "rest"): - client = ServicesClient( - 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.delete_service( - service.DeleteServiceRequest(), - name="name_value", - ) - - -def test_delete_service_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.get_iam_policy(request) @pytest.mark.parametrize( @@ -6115,10 +6863,9 @@ def test_delete_service_rest_error(): dict, ], ) -def test_get_iam_policy_rest(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -6134,11 +6881,10 @@ def test_get_iam_policy_rest(request_type): ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_iam_policy(request) @@ -6148,144 +6894,140 @@ def test_get_iam_policy_rest(request_type): assert response.etag == b"etag_blob" -def test_get_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_iam_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc - - request = {} - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_iam_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.GetIamPolicyRequest, -): - transport_class = transports.ServicesRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) + client = ServicesClient(transport=transport) - # verify fields with default values are dropped + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServicesRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - # verify required fields with default values are now present + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() - jsonified_request["resource"] = "resource_value" + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("options",)) - jsonified_request.update(unset_fields) + pre.assert_called_once() + post.assert_called_once() - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/sample3"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # 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 - 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 - - json_return_value = json_format.MessageToJson(return_value) + # 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.set_iam_policy(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_iam_policy(request) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest_call_success(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # send a request that will satisfy transcoding + request_init = {"resource": "projects/sample1/locations/sample2/services/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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("options",)) & set(("resource",))) + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.ServicesRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), ) client = ServicesClient(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.ServicesRestInterceptor, "post_get_iam_policy" + transports.ServicesRestInterceptor, "post_set_iam_policy" ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_get_iam_policy" + transports.ServicesRestInterceptor, "pre_set_iam_policy" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6293,12 +7035,12 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() + req.return_value = mock.Mock() req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) + req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6306,7 +7048,7 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = policy_pb2.Policy() - client.get_iam_policy( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -6318,14 +7060,12 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding request_init = {"resource": "projects/sample1/locations/sample2/services/sample3"} request = request_type(**request_init) @@ -6335,30 +7075,25 @@ def test_get_iam_policy_rest_bad_request( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = Request() + response_value.request = mock.Mock() req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.test_iam_permissions(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + iam_policy_pb2.TestIamPermissionsRequest, dict, ], ) -def test_set_iam_policy_rest(request_type): +def test_test_iam_permissions_rest_call_success(request_type): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -6368,214 +7103,268 @@ def test_set_iam_policy_rest(request_type): # 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], ) # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_iam_policy(request) + response = client.test_iam_permissions(request) # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] -def test_set_iam_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.ServicesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + ) + client = ServicesClient(transport=transport) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ServicesRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.ServicesRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Ensure method has been cached - assert client._transport.set_iam_policy in client._transport._wrapped_methods + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + req.return_value.content = return_value - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc - request = {} - client.set_iam_policy(request) + pre.assert_called_once() + post.assert_called_once() - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.set_iam_policy(request) +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) -def test_set_iam_policy_rest_required_fields( - request_type=iam_policy_pb2.SetIamPolicyRequest, -): - transport_class = transports.ServicesRestTransport +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - request_init = {} - request_init["resource"] = "" + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None - # verify fields with default values are dropped + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + req.return_value = response_value - # verify required fields with default values are now present + response = client.delete_operation(request) - jsonified_request["resource"] = "resource_value" + # Establish that the response is the type that we expect. + assert response is None - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) # 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 - 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 + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() - json_return_value = json_format.MessageToJson(return_value) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + req.return_value = response_value - response = client.set_iam_policy(request) + response = client.get_operation(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "resource", - "policy", - ) - ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request ) + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.ServicesRestTransport( +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + transport="rest", ) - client = ServicesClient(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.ServicesRestInterceptor, "post_set_iam_policy" - ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_set_iam_policy" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - 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 = json_format.MessageToJson(policy_pb2.Policy()) + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() - request = iam_policy_pb2.SetIamPolicyRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - client.set_iam_policy( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + req.return_value = response_value - pre.assert_called_once() - post.assert_called_once() + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_set_iam_policy_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, ): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) - - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/services/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( @@ -6583,377 +7372,363 @@ def test_set_iam_policy_rest_bad_request( ): # Wrap the value into a proper Response obj response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_error(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.wait_operation(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, + operations_pb2.WaitOperationRequest, dict, ], ) -def test_test_iam_permissions_rest(request_type): +def test_wait_operation_rest(request_type): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/services/sample3"} + request_init = {"name": "projects/sample1/locations/sample2/operations/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: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj - response_value = Response() + response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - -def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + response = client.wait_operation(request) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) - # Ensure method has been cached - assert ( - client._transport.test_iam_permissions in client._transport._wrapped_methods - ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.test_iam_permissions - ] = mock_rpc +def test_initialize_client_w_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None - request = {} - client.test_iam_permissions(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_service_empty_call_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - client.test_iam_permissions(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + client.create_service(request=None) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest() + assert args[0] == request_msg -def test_test_iam_permissions_rest_required_fields( - request_type=iam_policy_pb2.TestIamPermissionsRequest, -): - transport_class = transports.ServicesRestTransport - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_service_empty_call_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = "resource_value" - jsonified_request["permissions"] = "permissions_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + client.get_service(request=None) - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == "permissions_value" + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetServiceRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_services_empty_call_rest(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # 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 - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + client.list_services(request=None) - response_value = Response() - response_value.status_code = 200 + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListServicesRequest() - json_return_value = json_format.MessageToJson(return_value) + assert args[0] == request_msg - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.test_iam_permissions(request) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_service_empty_call_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + client.update_service(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest() -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.ServicesRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + assert args[0] == request_msg - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "resource", - "permissions", - ) - ) + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_service_empty_call_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + client.delete_service(request=None) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.ServicesRestTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteServiceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_iam_policy_empty_call_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServicesRestInterceptor(), + transport="rest", ) - client = ServicesClient(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.ServicesRestInterceptor, "post_test_iam_permissions" - ) as post, mock.patch.object( - transports.ServicesRestInterceptor, "pre_test_iam_permissions" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=None) - client.test_iam_permissions( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() - pre.assert_called_once() - post.assert_called_once() + assert args[0] == request_msg -def test_test_iam_permissions_rest_bad_request( - transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest -): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_set_iam_policy_empty_call_rest(): client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/locations/sample2/services/sample3"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=None) - # 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.test_iam_permissions(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + + assert args[0] == request_msg -def test_test_iam_permissions_rest_error(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_rest(): client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServicesGrpcTransport( + assert args[0] == request_msg + + +def test_create_service_routing_parameters_request_1_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_service), "__call__") as call: + client.create_service(request={"parent": "projects/sample1/locations/sample2"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.CreateServiceRequest( + **{"parent": "projects/sample1/locations/sample2"} ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ServicesGrpcTransport( + +def test_get_service_routing_parameters_request_1_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServicesClient( - client_options=options, - transport=transport, + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_service), "__call__") as call: + client.get_service( + request={"name": "projects/sample1/locations/sample2/sample3"} ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServicesClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.GetServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} ) - # It is an error to provide scopes and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( +def test_list_services_routing_parameters_request_1_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = ServicesClient(transport=transport) - assert client.transport is transport + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + client.list_services(request={"parent": "projects/sample1/locations/sample2"}) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.ListServicesRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_update_service_routing_parameters_request_1_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ServicesGrpcAsyncIOTransport( + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_service), "__call__") as call: + client.update_service( + request={"service": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = gcr_service.UpdateServiceRequest( + **{"service": {"name": "projects/sample1/locations/sample2/sample3"}} + ) + + assert args[0] == request_msg + + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_service_routing_parameters_request_1_rest(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_service), "__call__") as call: + client.delete_service( + request={"name": "projects/sample1/locations/sample2/sample3"} + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, - transports.ServicesRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = service.DeleteServiceRequest( + **{"name": "projects/sample1/locations/sample2/sample3"} + ) + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = ServicesClient.get_transport_class(transport_name)( + expected_headers = {"location": "sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_services_rest_lro_client(): + client = ServicesClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, ) - assert transport.kind == transport_name + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client def test_transport_grpc_default(): @@ -7198,23 +7973,6 @@ def test_services_http_transport_client_cert_source_for_mtls(): mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -def test_services_rest_lro_client(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - @pytest.mark.parametrize( "transport_name", [ @@ -7660,375 +8418,129 @@ def test_parse_service_path(): def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = ServicesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = ServicesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = ServicesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = ServicesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = ServicesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = ServicesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format( - project=project, - ) - actual = ServicesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = ServicesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = ServicesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = ServicesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.ServicesTransport, "_prep_wrapped_messages" - ) as prep: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.ServicesTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = ServicesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ServicesClient.common_billing_account_path(billing_account) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = ServicesClient.common_billing_account_path(**expected) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_billing_account_path(path) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ServicesClient.common_folder_path(folder) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = ServicesClient.common_folder_path(**expected) -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_folder_path(path) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, ) + actual = ServicesClient.common_organization_path(organization) + assert expected == actual - # 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.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = ServicesClient.common_organization_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_organization_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = ServicesClient.common_project_path(project) + assert expected == actual - response = client.list_operations(request) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = ServicesClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_project_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) + actual = ServicesClient.common_location_path(project, location) + assert expected == actual - # 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.wait_operation(request) +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = ServicesClient.common_location_path(**expected) -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_location_path(path) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() - response = client.wait_operation(request) + with mock.patch.object( + transports.ServicesTransport, "_prep_wrapped_messages" + ) as prep: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + with mock.patch.object( + transports.ServicesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ServicesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -8058,7 +8570,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8111,7 +8623,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8156,7 +8668,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -8197,7 +8709,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8252,7 +8764,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8299,7 +8811,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -8342,7 +8854,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8397,7 +8909,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8444,7 +8956,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -8487,7 +8999,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -8542,7 +9054,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -8589,7 +9101,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -8605,22 +9117,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ServicesAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_tasks.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_tasks.py index 076f21f71989..689697ac8deb 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_tasks.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_tasks.py @@ -22,12 +22,29 @@ except ImportError: # pragma: NO COVER import mock -from collections.abc import Iterable +from collections.abc import AsyncIterable, Iterable import json import math +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template -from google.api_core import api_core_version, client_options +from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries import google.auth @@ -37,15 +54,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -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.run_v2.services.tasks import ( TasksAsyncClient, @@ -56,10 +65,24 @@ from google.cloud.run_v2.types import condition, k8s_min, task, vendor_settings +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. @@ -1118,25 +1141,6 @@ def test_get_task(request_type, transport: str = "grpc"): assert response.etag == "etag_value" -def test_get_task_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_task), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == task.GetTaskRequest() - - def test_get_task_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1200,51 +1204,13 @@ def test_get_task_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_get_task_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_task), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - task.Task( - name="name_value", - uid="uid_value", - generation=1068, - job="job_value", - execution="execution_value", - max_retries=1187, - service_account="service_account_value", - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, - reconciling=True, - observed_generation=2021, - index=536, - retried=751, - encryption_key="encryption_key_value", - log_uri="log_uri_value", - satisfies_pzs=True, - etag="etag_value", - ) - ) - response = await client.get_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == task.GetTaskRequest() - - @pytest.mark.asyncio async def test_get_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1283,7 +1249,7 @@ async def test_get_task_async( transport: str = "grpc_asyncio", request_type=task.GetTaskRequest ): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1382,7 +1348,7 @@ def test_get_task_field_headers(): @pytest.mark.asyncio async def test_get_task_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1450,7 +1416,7 @@ def test_get_task_flattened_error(): @pytest.mark.asyncio async def test_get_task_flattened_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1477,7 +1443,7 @@ async def test_get_task_flattened_async(): @pytest.mark.asyncio async def test_get_task_flattened_error_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1525,25 +1491,6 @@ def test_list_tasks(request_type, transport: str = "grpc"): assert response.next_page_token == "next_page_token_value" -def test_list_tasks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == task.ListTasksRequest() - - def test_list_tasks_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. @@ -1609,36 +1556,13 @@ def test_list_tasks_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_list_tasks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - task.ListTasksResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == task.ListTasksRequest() - - @pytest.mark.asyncio async def test_list_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1677,7 +1601,7 @@ async def test_list_tasks_async( transport: str = "grpc_asyncio", request_type=task.ListTasksRequest ): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -1743,7 +1667,7 @@ def test_list_tasks_field_headers(): @pytest.mark.asyncio async def test_list_tasks_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1813,7 +1737,7 @@ def test_list_tasks_flattened_error(): @pytest.mark.asyncio async def test_list_tasks_flattened_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1842,7 +1766,7 @@ async def test_list_tasks_flattened_async(): @pytest.mark.asyncio async def test_list_tasks_flattened_error_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened @@ -1952,7 +1876,7 @@ def test_list_tasks_pages(transport_name: str = "grpc"): @pytest.mark.asyncio async def test_list_tasks_async_pager(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2002,7 +1926,7 @@ async def test_list_tasks_async_pager(): @pytest.mark.asyncio async def test_list_tasks_async_pages(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2048,81 +1972,6 @@ async def test_list_tasks_async_pages(): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "request_type", - [ - task.GetTaskRequest, - dict, - ], -) -def test_get_task_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" - } - 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 = task.Task( - name="name_value", - uid="uid_value", - generation=1068, - job="job_value", - execution="execution_value", - max_retries=1187, - service_account="service_account_value", - execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, - reconciling=True, - observed_generation=2021, - index=536, - retried=751, - encryption_key="encryption_key_value", - log_uri="log_uri_value", - satisfies_pzs=True, - etag="etag_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = task.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, task.Task) - assert response.name == "name_value" - assert response.uid == "uid_value" - assert response.generation == 1068 - assert response.job == "job_value" - assert response.execution == "execution_value" - assert response.max_retries == 1187 - assert response.service_account == "service_account_value" - assert ( - response.execution_environment - == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1 - ) - assert response.reconciling is True - assert response.observed_generation == 2021 - assert response.index == 536 - assert response.retried == 751 - assert response.encryption_key == "encryption_key_value" - assert response.log_uri == "log_uri_value" - assert response.satisfies_pzs is True - assert response.etag == "etag_value" - - def test_get_task_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2240,115 +2089,38 @@ def test_get_task_rest_unset_required_fields(): assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_rest_interceptors(null_interceptor): - transport = transports.TasksRestTransport( +def test_get_task_rest_flattened(): + client = TasksClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TasksRestInterceptor(), + transport="rest", ) - client = TasksClient(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.TasksRestInterceptor, "post_get_task" - ) as post, mock.patch.object( - transports.TasksRestInterceptor, "pre_get_task" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = task.GetTaskRequest.pb(task.GetTaskRequest()) - 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 = task.Task.to_json(task.Task()) + # 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 = task.Task() - request = task.GetTaskRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = task.Task() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" + } - client.get_task( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) + mock_args.update(sample_request) - pre.assert_called_once() - post.assert_called_once() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - -def test_get_task_rest_bad_request( - transport: str = "rest", request_type=task.GetTaskRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" - } - 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_task(request) - - -def test_get_task_rest_flattened(): - client = TasksClient( - 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 = task.Task() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" - } - - # 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 - # Convert return value to protobuf type - return_value = task.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_task(**mock_args) + client.get_task(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2376,54 +2148,6 @@ def test_get_task_rest_flattened_error(transport: str = "rest"): ) -def test_get_task_rest_error(): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - task.ListTasksRequest, - dict, - ], -) -def test_list_tasks_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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 = task.ListTasksResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = task.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_tasks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == "next_page_token_value" - - def test_list_tasks_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2558,85 +2282,6 @@ def test_list_tasks_rest_unset_required_fields(): ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tasks_rest_interceptors(null_interceptor): - transport = transports.TasksRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TasksRestInterceptor(), - ) - client = TasksClient(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.TasksRestInterceptor, "post_list_tasks" - ) as post, mock.patch.object( - transports.TasksRestInterceptor, "pre_list_tasks" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = task.ListTasksRequest.pb(task.ListTasksRequest()) - 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 = task.ListTasksResponse.to_json( - task.ListTasksResponse() - ) - - request = task.ListTasksRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = task.ListTasksResponse() - - client.list_tasks( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tasks_rest_bad_request( - transport: str = "rest", request_type=task.ListTasksRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" - } - 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.list_tasks(request) - - def test_list_tasks_rest_flattened(): client = TasksClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2828,41 +2473,727 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - transport = transports.TasksGrpcAsyncIOTransport( + transport = transports.TasksGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TasksGrpcTransport, + transports.TasksGrpcAsyncIOTransport, + transports.TasksRestTransport, + ], +) +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_transport_kind_grpc(): + transport = TasksClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_task_empty_call_grpc(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + call.return_value = task.Task() + client.get_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.GetTaskRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tasks_empty_call_grpc(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + call.return_value = task.ListTasksResponse() + client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.ListTasksRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TasksAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TasksAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_task_empty_call_grpc_asyncio(): + client = TasksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + task.Task( + name="name_value", + uid="uid_value", + generation=1068, + job="job_value", + execution="execution_value", + max_retries=1187, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + reconciling=True, + observed_generation=2021, + index=536, + retried=751, + encryption_key="encryption_key_value", + log_uri="log_uri_value", + satisfies_pzs=True, + etag="etag_value", + ) + ) + await client.get_task(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.GetTaskRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tasks_empty_call_grpc_asyncio(): + client = TasksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + task.ListTasksResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.ListTasksRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TasksClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_task_rest_bad_request(request_type=task.GetTaskRequest): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_task(request) + + +@pytest.mark.parametrize( + "request_type", + [ + task.GetTaskRequest, + dict, + ], +) +def test_get_task_rest_call_success(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4/tasks/sample5" + } + 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 = task.Task( + name="name_value", + uid="uid_value", + generation=1068, + job="job_value", + execution="execution_value", + max_retries=1187, + service_account="service_account_value", + execution_environment=vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1, + reconciling=True, + observed_generation=2021, + index=536, + retried=751, + encryption_key="encryption_key_value", + log_uri="log_uri_value", + satisfies_pzs=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = task.Task.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_task(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, task.Task) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.generation == 1068 + assert response.job == "job_value" + assert response.execution == "execution_value" + assert response.max_retries == 1187 + assert response.service_account == "service_account_value" + assert ( + response.execution_environment + == vendor_settings.ExecutionEnvironment.EXECUTION_ENVIRONMENT_GEN1 + ) + assert response.reconciling is True + assert response.observed_generation == 2021 + assert response.index == 536 + assert response.retried == 751 + assert response.encryption_key == "encryption_key_value" + assert response.log_uri == "log_uri_value" + assert response.satisfies_pzs is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_task_rest_interceptors(null_interceptor): + transport = transports.TasksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TasksRestInterceptor(), + ) + client = TasksClient(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.TasksRestInterceptor, "post_get_task" + ) as post, mock.patch.object( + transports.TasksRestInterceptor, "pre_get_task" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = task.GetTaskRequest.pb(task.GetTaskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = task.Task.to_json(task.Task()) + req.return_value.content = return_value + + request = task.GetTaskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = task.Task() + + client.get_task( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_tasks_rest_bad_request(request_type=task.ListTasksRequest): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_tasks(request) + + +@pytest.mark.parametrize( + "request_type", + [ + task.ListTasksRequest, + dict, + ], +) +def test_list_tasks_rest_call_success(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/jobs/sample3/executions/sample4" + } + 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 = task.ListTasksResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = task.ListTasksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_tasks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tasks_rest_interceptors(null_interceptor): + transport = transports.TasksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TasksRestInterceptor(), + ) + client = TasksClient(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.TasksRestInterceptor, "post_list_tasks" + ) as post, mock.patch.object( + transports.TasksRestInterceptor, "pre_list_tasks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = task.ListTasksRequest.pb(task.ListTasksRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = task.ListTasksResponse.to_json(task.ListTasksResponse()) + req.return_value.content = return_value + + request = task.ListTasksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = task.ListTasksResponse() + + client.list_tasks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "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(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_wait_operation_rest_bad_request( + request_type=operations_pb2.WaitOperationRequest, +): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.wait_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.WaitOperationRequest, + dict, + ], +) +def test_wait_operation_rest(request_type): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + + response = client.wait_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_task_empty_call_rest(): + client = TasksClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_task), "__call__") as call: + client.get_task(request=None) -@pytest.mark.parametrize( - "transport_class", - [ - transports.TasksGrpcTransport, - transports.TasksGrpcAsyncIOTransport, - transports.TasksRestTransport, - ], -) -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() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.GetTaskRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "rest", - ], -) -def test_transport_kind(transport_name): - transport = TasksClient.get_transport_class(transport_name)( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tasks_empty_call_rest(): + client = TasksClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + client.list_tasks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = task.ListTasksRequest() + + assert args[0] == request_msg def test_transport_grpc_default(): @@ -3469,377 +3800,131 @@ def test_parse_task_path(): } path = TasksClient.task_path(**expected) - # Check that the path construction is reversible. - actual = TasksClient.parse_task_path(path) - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = TasksClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = TasksClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TasksClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format( - folder=folder, - ) - actual = TasksClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = TasksClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TasksClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = TasksClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = TasksClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TasksClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format( - project=project, - ) - actual = TasksClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = TasksClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TasksClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = TasksClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = TasksClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TasksClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.TasksTransport, "_prep_wrapped_messages") as prep: - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TasksTransport, "_prep_wrapped_messages") as prep: - transport_class = TasksClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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.delete_operation(request) - - -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "{}" - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.GetOperationRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - - # 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_operation(request) + # Check that the path construction is reversible. + actual = TasksClient.parse_task_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + actual = TasksClient.common_billing_account_path(billing_account) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_operation(request) +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = TasksClient.common_billing_account_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + # Check that the path construction is reversible. + actual = TasksClient.parse_common_billing_account_path(path) + assert expected == actual -def test_list_operations_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.ListOperationsRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, ) + actual = TasksClient.common_folder_path(folder) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # 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.list_operations(request) +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = TasksClient.common_folder_path(**expected) + # Check that the path construction is reversible. + actual = TasksClient.parse_common_folder_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {"name": "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 = operations_pb2.ListOperationsResponse() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = TasksClient.common_organization_path(organization) + assert expected == actual - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_operations(request) +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = TasksClient.common_organization_path(**expected) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + # Check that the path construction is reversible. + actual = TasksClient.parse_common_organization_path(path) + assert expected == actual -def test_wait_operation_rest_bad_request( - transport: str = "rest", request_type=operations_pb2.WaitOperationRequest -): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, ) + actual = TasksClient.common_project_path(project) + assert expected == actual - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # 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.wait_operation(request) +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = TasksClient.common_project_path(**expected) + # Check that the path construction is reversible. + actual = TasksClient.parse_common_project_path(path) + assert expected == actual -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.WaitOperationRequest, - dict, - ], -) -def test_wait_operation_rest(request_type): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, ) - request_init = {"name": "projects/sample1/locations/sample2/operations/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 = operations_pb2.Operation() + actual = TasksClient.common_location_path(project, location) + assert expected == actual - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = TasksClient.common_location_path(**expected) - response = client.wait_operation(request) + # Check that the path construction is reversible. + actual = TasksClient.parse_common_location_path(path) + assert expected == actual - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.TasksTransport, "_prep_wrapped_messages") as prep: + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TasksTransport, "_prep_wrapped_messages") as prep: + transport_class = TasksClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) def test_delete_operation(transport: str = "grpc"): @@ -3869,7 +3954,7 @@ def test_delete_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -3922,7 +4007,7 @@ def test_delete_operation_field_headers(): @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -3967,7 +4052,7 @@ def test_delete_operation_from_dict(): @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: @@ -4008,7 +4093,7 @@ def test_wait_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_wait_operation(transport: str = "grpc_asyncio"): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4063,7 +4148,7 @@ def test_wait_operation_field_headers(): @pytest.mark.asyncio async def test_wait_operation_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4110,7 +4195,7 @@ def test_wait_operation_from_dict(): @pytest.mark.asyncio async def test_wait_operation_from_dict_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.wait_operation), "__call__") as call: @@ -4153,7 +4238,7 @@ def test_get_operation(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4208,7 +4293,7 @@ def test_get_operation_field_headers(): @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4255,7 +4340,7 @@ def test_get_operation_from_dict(): @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_operation), "__call__") as call: @@ -4298,7 +4383,7 @@ def test_list_operations(transport: str = "grpc"): @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), transport=transport, ) @@ -4353,7 +4438,7 @@ def test_list_operations_field_headers(): @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -4400,7 +4485,7 @@ def test_list_operations_from_dict(): @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = TasksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_operations), "__call__") as call: @@ -4416,22 +4501,41 @@ async def test_list_operations_from_dict_async(): call.assert_called() -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } +def test_transport_close_grpc(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() - for transport, close_name in transports.items(): - client = TasksClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport - ) - with mock.patch.object( - type(getattr(client.transport, close_name)), "close" - ) as close: - with client: - close.assert_not_called() - close.assert_called_once() + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = TasksAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = TasksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() def test_client_ctx(): diff --git a/scripts/client-post-processing/sub-api-versioned-namespace.yaml b/scripts/client-post-processing/sub-api-versioned-namespace.yaml index c48b104a9692..68f92a02dde1 100644 --- a/scripts/client-post-processing/sub-api-versioned-namespace.yaml +++ b/scripts/client-post-processing/sub-api-versioned-namespace.yaml @@ -96,6 +96,7 @@ replacements: packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/base.py, packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py, packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py, + packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest_base.py, packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/rest.py, packages/google-cloud-os-login/google/cloud/oslogin_v1/types/oslogin.py, packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py, @@ -104,7 +105,7 @@ replacements: from google.cloud.oslogin.common.types import common after: | from google.cloud.oslogin_v1.common.types import common - count: 8 + count: 9 - paths: [ packages/google-cloud-os-login/docs/index.rst, ]